import { useState } from 'react';
import { Globe, Phone, Download, User as UserIcon, Smartphone } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

export default function TransactionHistory({ user }) {
  const navigate = useNavigate();
  const [dateRange] = useState({ start: '04 Dec 2025', end: '04 Dec 2025' });
  const [ownerPhone] = useState('+919344489998'); // Owner phone number

  // Sample transaction data
  const transactions = [
    { id: 1, date: '04 Dec', debit: 500, credit: null, isLatest: true },
    { id: 2, date: '04 Dec', debit: 200, credit: null, isLatest: false },
    { id: 3, date: '04 Dec', debit: null, credit: 200, isLatest: false },
    { id: 4, date: '04 Dec', debit: null, credit: 1000, isLatest: false },
    { id: 5, date: '04 Dec', debit: 1000, credit: null, isLatest: false },
  ];

  // Calculate running balance
  const calculateTransactions = () => {
    let balance = 0;
    const transactionsWithBalance = [];
    
    for (let i = transactions.length - 1; i >= 0; i--) {
      const txn = transactions[i];
      if (txn.debit) {
        balance += txn.debit;
      }
      if (txn.credit) {
        balance -= txn.credit;
      }
      transactionsWithBalance.unshift({
        ...txn,
        balance,
      });
    }
    
    return transactionsWithBalance;
  };

  const transactionsWithBalance = calculateTransactions();
  const totalDebit = transactions.reduce((sum, txn) => sum + (txn.debit || 0), 0);
  const totalCredit = transactions.reduce((sum, txn) => sum + (txn.credit || 0), 0);
  const netBalance = totalDebit - totalCredit;

  const formatBalance = (balance) => {
    if (balance === 0) return '0';
    if (balance > 0) return `${balance.toLocaleString('en-IN')} Dr`;
    return `${Math.abs(balance).toLocaleString('en-IN')} Cr`;
  };

  const getBalanceColor = (balance) => {
    if (balance === 0) return 'text-gray-900';
    if (balance > 0) return 'text-red-600';
    return 'text-green-600';
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 shadow-sm" style={{ maxWidth: '800px', width: '100%' }}>
        <div className="px-4 md:px-6 py-3 md:py-4">
          <div className="flex items-center justify-between gap-2">
            {/* Logo */}
            <div 
              className="text-white px-4 py-2 md:px-6 md:py-3 rounded-lg font-bold text-base md:text-xl shadow-md cursor-pointer"
              style={{ background: 'linear-gradient(to right, #FF6B00, #FF8534)' }}
              onClick={() => navigate('/dashboard')}
            >
              LedgerPro
            </div>

            {/* Actions */}
            <div className="flex items-center gap-2 md:gap-4">
              <button className="flex items-center gap-1 md:gap-2 px-2 md:px-4 py-1.5 md:py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                <Globe className="w-3 h-3 md:w-4 md:h-4" />
                <span className="text-xs md:text-sm font-medium hidden sm:inline">English</span>
              </button>
              <button className="flex items-center gap-1 md:gap-2 px-2 md:px-4 py-1.5 md:py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                <Phone className="w-3 h-3 md:w-4 md:h-4" />
                <span className="text-xs md:text-sm font-medium hidden sm:inline">Call Support</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="px-4 md:px-6 py-6 md:py-8" style={{ maxWidth: '800px', width: '100%' }}>
        {/* Owner Contact Card */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 px-4 py-4 md:px-6 mb-6">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3 md:gap-4 flex-1 min-w-0">
              <div className="w-12 h-12 md:w-14 md:h-14 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0">
                <UserIcon className="w-6 h-6 md:w-7 md:h-7 text-gray-500" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-xs text-gray-500 font-medium mb-1">Owner Contact</p>
                <p className="text-lg md:text-xl font-bold text-gray-900 truncate">{ownerPhone}</p>
              </div>
            </div>
            <a 
              href={`tel:${ownerPhone}`}
              className="w-14 h-14 md:w-16 md:h-16 bg-green-500 rounded-full flex items-center justify-center hover:bg-green-600 transition-colors shadow-lg flex-shrink-0"
              title="Call Owner"
              style={{ backgroundColor: '#10b981' }}
            >
              <Phone className="w-6 h-6 md:w-8 md:h-8 text-white" />
            </a>
          </div>
        </div>

        {/* Title on Left, Summary Card on Right - Same Row (Desktop) / Stacked (Mobile/Tablet) */}
        <div className="flex flex-col lg:flex-row items-start justify-between gap-4 mb-4">
          {/* Left: Title */}
          <div className="w-full lg:w-auto">
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-1">Transaction History</h1>
            <p className="text-sm md:text-base text-gray-500">({dateRange.start} - {dateRange.end})</p>
          </div>

          {/* Right: Summary Card */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 px-4 py-4 md:px-6 w-full lg:w-auto lg:min-w-[550px]">
            <div className="grid grid-cols-3 gap-4 md:gap-6 max-sm:grid-cols-[repeat(auto-fit,minmax(100px,1fr))]">
              <div className="text-center">
                <div className="text-xs md:text-sm text-gray-500 font-medium mb-1">Total Debit(-)</div>
                <div className="text-2xl md:text-3xl font-bold text-gray-900">₹{totalDebit.toLocaleString('en-IN')}</div>
              </div>

              <div className="text-center">
                <div className="text-xs md:text-sm text-gray-500 font-medium mb-1">Total Credit(+)</div>
                <div className="text-2xl md:text-3xl font-bold text-gray-900">₹{totalCredit.toLocaleString('en-IN')}</div>
              </div>

              <div className="text-center">
                <div className="text-xs md:text-sm text-gray-500 font-medium mb-1">Net Balance</div>
                <div className={`text-2xl md:text-3xl font-bold ${getBalanceColor(netBalance)}`}>
                  ₹{formatBalance(Math.abs(netBalance))}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Transaction Table - Full Width */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[600px]">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-300">
                  <th className="px-3 md:px-6 py-3 text-left text-xs md:text-sm font-semibold text-gray-700 border-r border-gray-300">Date</th>
                  <th className="px-3 md:px-6 py-3 text-right text-xs md:text-sm font-semibold text-gray-700 border-r border-gray-300">Debit(-)</th>
                  <th className="px-3 md:px-6 py-3 text-right text-xs md:text-sm font-semibold text-gray-700 border-r border-gray-300">Credit(+)</th>
                  <th className="px-3 md:px-6 py-3 text-right text-xs md:text-sm font-semibold text-gray-700">Balance</th>
                </tr>
              </thead>
              <tbody>
                {transactionsWithBalance.map((transaction) => {
                  const rowBgColor = transaction.debit ? 'bg-red-50' : transaction.credit ? 'bg-green-50' : '';
                  
                  return (
                    <tr key={transaction.id} className={`border-b border-gray-300 ${rowBgColor}`}>
                      <td className="px-3 md:px-6 py-3 border-r border-gray-300">
                        <div className="flex flex-col">
                          {transaction.isLatest && (
                            <span className="text-xs font-semibold text-gray-500 mb-0.5">Latest</span>
                          )}
                          <span className="text-xs md:text-sm font-medium text-gray-900">{transaction.date}</span>
                        </div>
                      </td>

                      <td className="px-3 md:px-6 py-3 text-right border-r border-gray-300">
                        {transaction.debit ? (
                          <span className="text-xs md:text-sm font-semibold text-gray-900">
                            {transaction.debit.toLocaleString('en-IN')}
                          </span>
                        ) : (
                          <span className="text-gray-400">—</span>
                        )}
                      </td>

                      <td className="px-3 md:px-6 py-3 text-right border-r border-gray-300">
                        {transaction.credit ? (
                          <span className="text-xs md:text-sm font-semibold text-gray-900">
                            {transaction.credit.toLocaleString('en-IN')}
                          </span>
                        ) : (
                          <span className="text-gray-400">—</span>
                        )}
                      </td>

                      <td className="px-3 md:px-6 py-3 text-right">
                        <span className={`font-bold text-xs md:text-sm ${getBalanceColor(transaction.balance)}`}>
                          {formatBalance(transaction.balance)}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* App Download Banner */}
        <div className="mt-8 bg-gradient-to-r from-blue-600 via-blue-500 to-orange-500 rounded-xl shadow-lg overflow-hidden">
          <div className="px-4 md:px-8 py-6 md:py-8">
            <div className="flex flex-col md:flex-row items-start justify-between gap-6">
              {/* Left: Text Content */}
              <div className="flex-1 text-left text-white">
                <h2 className="text-2xl md:text-3xl font-bold text-black mb-2 text-white">
                  Digitize Your Ledger,<br />
                  Simplify Your Business!
                </h2>
                <p className="text-black text-sm md:text-base mb-4 text-white">
                  Manage all your transactions on the go with LedgerPro App
                </p>
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    // TODO: Add actual Play Store link when app is ready
                    alert('App download link will be available soon!');
                  }}
                  className="inline-flex flex-row items-center gap-3 font-bold px-6 py-3 rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 cursor-pointer active:scale-95"
                  style={{ backgroundColor: '#2563eb', color: '#ffffff', display: 'inline-flex', flexDirection: 'row', alignItems: 'center' }}
                  onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#1d4ed8'}
                  onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#2563eb'}
                >
                  <Smartphone className="w-5 h-5 flex-shrink-0" style={{ color: '#ffffff' }} />
                  <span style={{ whiteSpace: 'nowrap' }}>Download LedgerPro</span>
                </button>
              </div>

              {/* Right: Phone Icon/Placeholder */}
              <div className="flex-shrink-0">
                <div className="w-32 h-32 md:w-40 md:h-40 bg-white/20 rounded-2xl flex items-center justify-center backdrop-blur-sm">
                  <Smartphone className="w-16 h-16 md:w-20 md:h-20 text-white" />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-6 text-center text-sm text-gray-500">
          <p>Showing {transactions.length} transactions</p>
        </div>
      </div>
    </div>
  );
}
