import React, { useState } from "react";
import { applications, financeRows, transactions } from "../../data/mockData";

export function TransactionList({ role, title }) {
  const [apps, setApps] = useState(applications);
  const [approvedCredentials, setApprovedCredentials] = useState(null);

  const handleApprove = (application) => {
    // Simulating the backend response from reviewApplication controller
    const tempPassword = Math.random().toString(36).slice(-8);
    
    // Update local state to mark as active
    setApps(prev => prev.map(a => a.name === application.name ? { ...a, status: 'active' } : a));
    
    setApprovedCredentials({
      owner_name: application.name,
      username: application.name.toLowerCase().replace(/\s/g, ".") + "@notary.so",
      temporary_password: tempPassword
    });
  };

  if (role === "ministry_finance") {
    return (
      <section className="card table-card">
        <div className="section-header">
          <h3>{title}</h3>
          <div className="inline-actions">
            <button className="ghost-button">Export Excel</button>
            <button className="ghost-button">Export PDF</button>
          </div>
        </div>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Transaction ID</th>
                <th>Service</th>
                <th>Asset</th>
                <th>Notary</th>
                <th>Region</th>
                <th>District</th>
                <th>Customer</th>
                <th>Paid</th>
                <th>Reference</th>
                <th>Phone</th>
                <th>Commodity</th>
                <th>MOF Tax</th>
                <th>Notary Fee</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              {financeRows.map((row) => (
                <tr key={row[0]}>
                  {row.map((cell, index) => (
                    <td key={`${row[0]}-${index}`}>{cell}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    );
  }

  if (role === "ministry_justice") {
    return (
      <section className="card table-card">
        <div className="section-header">
          <h3>{title}</h3>
          <button className="solid-button">Review Queue</button>
        </div>
        <div className="application-list">
          {apps.map((item) => (
            <article key={item.name} className="application-item">
              <div>
                <strong>{item.name}</strong>
                <p>
                  {item.region} • {item.district} • Category {item.category}
                </p>
              </div>
              <div className="row-end">
                <span className={`status-chip ${item.status}`}>{item.status}</span>
                {item.status === 'pending' && (
                  <button 
                    className="solid-button sm" 
                    onClick={() => handleApprove(item)}
                    style={{ padding: '4px 12px', fontSize: '0.85rem' }}
                  >
                    Approve
                  </button>
                )}
              </div>
            </article>
          ))}
        </div>

        {approvedCredentials && (
          <div className="credentials-overlay" style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0,0,0,0.5)',
            display: 'grid',
            placeItems: 'center',
            zIndex: 1000,
            padding: '20px'
          }}>
            <div className="card credentials-card" style={{ maxWidth: '400px', width: '100%' }}>
              <h3>Application Approved!</h3>
              <p className="login-copy">The following credentials have been generated for the Notary Owner:</p>
              
              <div className="demo-card" style={{ margin: '20px 0', padding: '16px', background: 'var(--accent-soft)', borderRadius: '12px', border: '1px dashed var(--accent)' }}>
                <p><strong>Owner Account:</strong> {approvedCredentials.owner_name}</p>
                <p><strong>Username:</strong> {approvedCredentials.username}</p>
                <p><strong>Temp Password:</strong> <code>{approvedCredentials.temporary_password}</code></p>
              </div>

              <p style={{ fontSize: '0.85rem', color: '#61756f', marginBottom: '20px' }}>
                Please share these credentials with the applicant. They will be required to change their password upon first login.
              </p>

              <button 
                className="solid-button" 
                style={{ width: '100%' }}
                onClick={() => setApprovedCredentials(null)}
              >
                Close & Continue
              </button>
            </div>
          </div>
        )}
      </section>
    );
  }

  return (
    <section className="card table-card">
      <div className="section-header">
        <h3>{title}</h3>
        <button className="solid-button">New Transaction</button>
      </div>
      <div className="list-stack">
        {transactions.map((item) => (
          <article key={item.id} className="transaction-item">
            <div>
              <p className="eyebrow">{item.type}</p>
              <strong>{item.client}</strong>
              <p>{item.asset} • {item.details}</p>
            </div>
            <div style={{ textAlign: "right" }}>
              <strong>${item.amount}</strong>
              <span className={`status-chip ${item.status}`}>{item.status}</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}
