'use client';

import { useState, useMemo } from 'react';
import Price from '@/components/Price';
import { manualMatch, unmatchBankLine, markReconciled, archiveStatement } from './actions';

interface BankStatement {
  id: string;
  filename: string;
  status: string;
  lines: {
    id: string;
    date: Date;
    description: string;
    amount: number;
    matched: boolean;
  }[];
  reconciliations: {
    id: string;
    bankLineId: string;
    transactionType: string;
    transactionId: string | null;
    description: string;
    systemAmount: number;
    bankAmount: number;
    amountMatches: boolean;
    confidence: number;
    notes: string | null;
    matchedAt: Date;
    matchedBy: string | null;
    statementId: string;
  }[];
}

export default function ReconciliationClient({ statement }: { statement: BankStatement }) {
  const [activeTab, setActiveTab] = useState<'matched' | 'unmatched' | 'discrepancies'>('unmatched');
  const [matchingBankLineId, setMatchingBankLineId] = useState<string | null>(null);
  const [sortBy, setSortBy] = useState<{ field: string; order: 'asc' | 'desc' }>({ field: 'date', order: 'desc' });

  // Categorize lines
  const unmatchedLines = useMemo(() => {
    return statement.lines.filter((line) => !line.matched).sort((a, b) => {
      if (sortBy.order === 'desc') return b.date.getTime() - a.date.getTime();
      return a.date.getTime() - b.date.getTime();
    });
  }, [statement.lines, sortBy]);

  const matchedLines = useMemo(() => {
    return statement.lines
      .filter((line) => line.matched)
      .map((line) => {
        const recon = statement.reconciliations.find((r) => r.bankLineId === line.id);
        return { line, recon };
      })
      .sort((a, b) => {
        if (sortBy.order === 'desc') return b.line.date.getTime() - a.line.date.getTime();
        return a.line.date.getTime() - b.line.date.getTime();
      });
  }, [statement.lines, statement.reconciliations, sortBy]);

  const discrepancies = useMemo(() => {
    return matchedLines.filter((m) => m.recon && !m.recon.amountMatches);
  }, [matchedLines]);

  const isReconciled = unmatchedLines.length === 0 && discrepancies.length === 0;

  const handleUnmatch = async (bankLineId: string) => {
    try {
      await unmatchBankLine(bankLineId);
      window.location.reload();
    } catch (err) {
      alert(`Failed to unmatch: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleMarkReconciled = async () => {
    if (!isReconciled) {
      alert('Please resolve all unmatched items and discrepancies first');
      return;
    }
    try {
      await markReconciled(statement.id);
      window.location.reload();
    } catch (err) {
      alert(`Failed to mark reconciled: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleArchive = async () => {
    if (!confirm('Archive this statement? You can still view it later.')) return;
    try {
      await archiveStatement(statement.id);
      window.location.href = '/admin/accounts/reconciliation';
    } catch (err) {
      alert(`Failed to archive: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  return (
    <div className="space-y-6">
      {/* Action Buttons */}
      <div className="flex flex-wrap gap-3">
        {isReconciled && statement.status !== 'RECONCILED' && (
          <button
            onClick={handleMarkReconciled}
            className="border border-green-600 bg-green-600 text-white px-4 py-2 text-sm hover:bg-green-700"
          >
            ✓ Mark Reconciled
          </button>
        )}
        {statement.status === 'RECONCILED' && (
          <button
            onClick={handleArchive}
            className="border border-line px-4 py-2 text-sm hover:bg-surface"
          >
            📦 Archive Statement
          </button>
        )}
      </div>

      {/* Tabs */}
      <div className="inline-flex border border-line">
        {[
          { id: 'unmatched', label: `Unmatched (${unmatchedLines.length})`, color: unmatchedLines.length > 0 ? 'text-splash-pink' : '' },
          { id: 'matched', label: `Matched (${matchedLines.length})`, color: matchedLines.length > 0 ? 'text-green-600' : '' },
          { id: 'discrepancies', label: `Discrepancies (${discrepancies.length})`, color: discrepancies.length > 0 ? 'text-orange-600' : '' },
        ].map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id as any)}
            className={`px-4 py-1.5 text-sm ${activeTab === tab.id ? 'bg-ink text-paper' : `hover:text-clay ${tab.color}`}`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Unmatched Items */}
      {activeTab === 'unmatched' && (
        <div>
          {unmatchedLines.length === 0 ? (
            <p className="text-sm text-muted py-8 text-center">All transactions matched! ✓</p>
          ) : (
            <div className="space-y-3">
              <p className="text-sm text-muted">Manually match these transactions to system records:</p>
              {unmatchedLines.map((line) => (
                <div key={line.id} className="border border-line p-4 space-y-3">
                  <div className="flex items-baseline justify-between">
                    <div>
                      <p className="font-medium">{line.description}</p>
                      <p className="text-xs text-muted font-mono">
                        {new Date(line.date).toLocaleDateString('en-GB')} • <Price cents={line.amount} />
                      </p>
                    </div>
                    <button
                      onClick={() => setMatchingBankLineId(matchingBankLineId === line.id ? null : line.id)}
                      className="text-sm text-clay hover:text-clay-dark"
                    >
                      {matchingBankLineId === line.id ? '✕ Close' : '🔗 Match'}
                    </button>
                  </div>

                  {matchingBankLineId === line.id && (
                    <ManualMatchForm
                      bankLineId={line.id}
                      bankAmount={line.amount}
                      onSuccess={() => {
                        setMatchingBankLineId(null);
                        window.location.reload();
                      }}
                    />
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Matched Items */}
      {activeTab === 'matched' && (
        <div className="overflow-x-auto">
          {matchedLines.length === 0 ? (
            <p className="text-sm text-muted py-8 text-center">No matched transactions yet</p>
          ) : (
            <table className="w-full border-collapse text-sm">
              <thead>
                <tr className="border-b border-line bg-surface">
                  <th className="text-left py-2 px-3 font-medium">Bank Date</th>
                  <th className="text-left py-2 px-3 font-medium">Description</th>
                  <th className="text-right py-2 px-3 font-medium">Bank Amount</th>
                  <th className="text-right py-2 px-3 font-medium">System Amount</th>
                  <th className="text-left py-2 px-3 font-medium">Type</th>
                  <th className="text-center py-2 px-3 font-medium">Action</th>
                </tr>
              </thead>
              <tbody>
                {matchedLines.map(({ line, recon }) => (
                  <tr key={line.id} className="border-b border-line hover:bg-surface">
                    <td className="py-2 px-3 font-mono text-xs">{new Date(line.date).toLocaleDateString('en-GB')}</td>
                    <td className="py-2 px-3 text-xs">{line.description}</td>
                    <td className="text-right py-2 px-3 font-mono">
                      <Price cents={line.amount} />
                    </td>
                    <td className="text-right py-2 px-3 font-mono">
                      <Price cents={recon?.systemAmount || 0} />
                    </td>
                    <td className="py-2 px-3 text-xs">{recon?.transactionType || '—'}</td>
                    <td className="text-center py-2 px-3">
                      <button
                        onClick={() => handleUnmatch(line.id)}
                        className="text-xs text-muted hover:text-splash-pink"
                      >
                        Unmatch
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* Discrepancies */}
      {activeTab === 'discrepancies' && (
        <div className="space-y-3">
          {discrepancies.length === 0 ? (
            <p className="text-sm text-muted py-8 text-center">No discrepancies! ✓</p>
          ) : (
            <>
              <p className="text-sm text-orange-600">
                ⚠ These items matched but the amounts don't match exactly. Review and correct if needed.
              </p>
              {discrepancies.map(({ line, recon }) => (
                <div key={line.id} className="border-2 border-orange-200 bg-orange-50 p-4 space-y-2">
                  <div className="flex items-baseline justify-between">
                    <div>
                      <p className="font-medium">{line.description}</p>
                      <p className="text-xs text-muted font-mono">{new Date(line.date).toLocaleDateString('en-GB')}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-muted">Bank vs System</p>
                      <p className="font-mono">
                        <Price cents={line.amount} /> vs <Price cents={recon?.systemAmount || 0} />
                      </p>
                      <p className="text-xs text-orange-600 font-medium">
                        Diff: <Price cents={Math.abs((line.amount || 0) - (recon?.systemAmount || 0))} />
                      </p>
                    </div>
                  </div>
                  <button
                    onClick={() => handleUnmatch(line.id)}
                    className="text-xs text-orange-600 hover:text-orange-700 hover:underline"
                  >
                    Unmatch and re-assign
                  </button>
                </div>
              ))}
            </>
          )}
        </div>
      )}
    </div>
  );
}

function ManualMatchForm({
  bankLineId,
  bankAmount,
  onSuccess,
}: {
  bankLineId: string;
  bankAmount: number;
  onSuccess: () => void;
}) {
  const [transactionType, setTransactionType] = useState<string>('ORDER');
  const [transactionId, setTransactionId] = useState('');
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!transactionId) {
      alert('Please enter a transaction ID');
      return;
    }

    setLoading(true);
    try {
      await manualMatch(bankLineId, transactionType, transactionId, notes);
      onSuccess();
    } catch (err) {
      alert(`Failed to match: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3 bg-surface p-4 rounded">
      <div className="grid gap-3 sm:grid-cols-2">
        <select
          value={transactionType}
          onChange={(e) => setTransactionType(e.target.value)}
          className="border border-line bg-paper px-3 py-2 text-sm"
        >
          <option value="ORDER">Order</option>
          <option value="MANUAL_SALE">Manual Sale</option>
          <option value="EXPENSE">Expense</option>
          <option value="OTHER">Other (specify in notes)</option>
        </select>

        <input
          type="text"
          value={transactionId}
          onChange={(e) => setTransactionId(e.target.value)}
          placeholder="Transaction ID or reference"
          className="border border-line bg-paper px-3 py-2 text-sm"
        />
      </div>

      <textarea
        value={notes}
        onChange={(e) => setNotes(e.target.value)}
        placeholder="Optional notes about this match..."
        className="w-full border border-line bg-paper px-3 py-2 text-sm"
        rows={2}
      />

      <div className="flex gap-2">
        <button
          type="submit"
          disabled={loading}
          className="border border-green-600 bg-green-600 text-white px-4 py-2 text-sm hover:bg-green-700 disabled:opacity-50"
        >
          {loading ? 'Matching...' : '✓ Confirm Match'}
        </button>
      </div>
    </form>
  );
}
