import { useEffect, useState } from 'react';
import { useWalletStore } from '../store/wallet';
import type { Transaction } from '../lib/rpc';

export default function HistoryPage() {
  const { address, transactions, refreshTransactions } = useWalletStore();
  const [selectedTx, setSelectedTx] = useState<Transaction | null>(null);

  useEffect(() => {
    refreshTransactions();
  }, [refreshTransactions]);

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString();
  };

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">Transaction History</h1>

      {transactions.length === 0 ? (
        <div className="card text-center py-12">
          <div className="text-6xl mb-4 text-slate-600">◇</div>
          <h2 className="text-xl font-semibold mb-2">No Transactions</h2>
          <p className="text-slate-400">
            Your transaction history will appear here.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {transactions.map((tx) => {
            const isReceived = tx.outputs.some((o) => o.address === address);
            const relevantOutputs = tx.outputs.filter((o) =>
              isReceived ? o.address === address : o.address !== address
            );
            const amount = relevantOutputs.reduce(
              (sum, o) => sum + parseFloat(o.amount),
              0
            );

            return (
              <button
                key={tx.id}
                onClick={() => setSelectedTx(tx)}
                className="w-full card hover:bg-slate-700 transition-colors text-left"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div
                      className={`w-10 h-10 rounded-full flex items-center justify-center ${
                        isReceived
                          ? 'bg-green-900/50 text-green-400'
                          : 'bg-red-900/50 text-red-400'
                      }`}
                    >
                      {isReceived ? '↓' : '↑'}
                    </div>
                    <div>
                      <div className="font-medium">
                        {isReceived ? 'Received' : 'Sent'}
                      </div>
                      <div className="text-sm text-slate-500">
                        {formatDate(tx.timestamp)}
                      </div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div
                      className={`font-semibold ${
                        isReceived ? 'text-green-400' : 'text-red-400'
                      }`}
                    >
                      {isReceived ? '+' : '-'}
                      {amount.toFixed(8)} SYNOR
                    </div>
                    <div className="text-sm text-slate-500">
                      {tx.confirmations > 0 ? (
                        <span className="text-green-400">
                          {tx.confirmations} confirmations
                        </span>
                      ) : (
                        <span className="text-yellow-400">Pending</span>
                      )}
                    </div>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      )}

      {/* Transaction Detail Modal */}
      {selectedTx && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="card max-w-lg w-full max-h-[80vh] overflow-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">Transaction Details</h2>
              <button
                onClick={() => setSelectedTx(null)}
                className="text-slate-400 hover:text-white text-2xl"
              >
                ×
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <div className="text-sm text-slate-400 mb-1">Transaction ID</div>
                <div className="font-mono text-sm break-all bg-slate-900 p-2 rounded">
                  {selectedTx.id}
                </div>
              </div>

              <div>
                <div className="text-sm text-slate-400 mb-1">Status</div>
                <div>
                  {selectedTx.confirmations > 0 ? (
                    <span className="text-green-400">
                      Confirmed ({selectedTx.confirmations} confirmations)
                    </span>
                  ) : (
                    <span className="text-yellow-400">Pending</span>
                  )}
                </div>
              </div>

              <div>
                <div className="text-sm text-slate-400 mb-1">Timestamp</div>
                <div>{formatDate(selectedTx.timestamp)}</div>
              </div>

              {selectedTx.blockHash && (
                <div>
                  <div className="text-sm text-slate-400 mb-1">Block Hash</div>
                  <div className="font-mono text-sm break-all bg-slate-900 p-2 rounded">
                    {selectedTx.blockHash}
                  </div>
                </div>
              )}

              <div>
                <div className="text-sm text-slate-400 mb-2">Inputs</div>
                <div className="space-y-2">
                  {selectedTx.inputs.map((input, i) => (
                    <div
                      key={i}
                      className="bg-slate-900 p-2 rounded font-mono text-xs"
                    >
                      {input.previousTxId}:{input.outputIndex}
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <div className="text-sm text-slate-400 mb-2">Outputs</div>
                <div className="space-y-2">
                  {selectedTx.outputs.map((output, i) => (
                    <div
                      key={i}
                      className="bg-slate-900 p-2 rounded flex justify-between"
                    >
                      <span className="font-mono text-xs truncate max-w-[200px]">
                        {output.address}
                      </span>
                      <span>{output.amount} SYNOR</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <button
              onClick={() => setSelectedTx(null)}
              className="w-full btn btn-secondary mt-6"
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
