import { useMemo } from 'react';
import { useExpenseStore } from '@/stores/expenseStore';
import { useFeeStore } from '@/stores/feeStore';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { useUIStore } from '@/stores/uiStore';
import { formatCurrency } from '@/lib/formatters';
import {
  IndianRupee, TrendingUp, TrendingDown, Package, Receipt, Wallet,
  ArrowRight, ChevronLeft, PlusCircle
} from 'lucide-react';

export default function ProfitDashboardScreen() {
  const { expenses } = useExpenseStore();
  const { receipts } = useFeeStore();
  const { transactions } = useEquipmentStore();
  const { goBack, navigateTo } = useUIStore();

  // ===== FEES BOARD =====
  const totalFeeRevenue = useMemo(() => receipts.reduce((s, r) => s + r.totalAmount, 0), [receipts]);
  const totalExpenses = useMemo(() => expenses.reduce((s, e) => s + e.amount, 0), [expenses]);
  const feeProfit = totalFeeRevenue - totalExpenses;

  // ===== EQUIPMENT BOARD =====
  const equipmentBuys = useMemo(() => transactions.filter(t => t.type === 'buy'), [transactions]);
  const equipmentSells = useMemo(() => transactions.filter(t => t.type === 'sell'), [transactions]);
  const totalEquipmentBuy = useMemo(() => equipmentBuys.reduce((s, t) => s + t.totalAmount, 0), [equipmentBuys]);
  const totalEquipmentRevenue = useMemo(() => equipmentSells.reduce((s, t) => s + t.totalAmount, 0), [equipmentSells]);
  const equipmentProfit = useMemo(() => equipmentSells.reduce((s, t) => s + (t.profit || 0), 0), [equipmentSells]);

  // ===== COMBINED BOARD =====
  const totalRevenue = totalFeeRevenue + totalEquipmentRevenue;
  const totalProfit = feeProfit + equipmentProfit;

  // Expenses by category
  const expenseBreakdown = useMemo(() => {
    const map: Record<string, number> = {};
    expenses.forEach(e => { map[e.category] = (map[e.category] || 0) + e.amount; });
    return Object.entries(map).sort((a, b) => b[1] - a[1]);
  }, [expenses]);

  const catLabels: Record<string, string> = {
    rent: 'Rent', salary: 'Salary', electricity: 'Electricity', water: 'Water',
    maintenance: 'Maintenance', transport: 'Transport', food: 'Food', other: 'Other',
  };

  return (
    <div className="px-4 pt-4 pb-4 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <button onClick={goBack} className="p-1"><ChevronLeft className="w-5 h-5 text-gray-500" /></button>
          <h2 className="text-lg font-bold text-gray-900">Profit Dashboard</h2>
        </div>
        <button onClick={() => navigateTo('addExpense')}
          className="flex items-center gap-1.5 px-3 py-2 bg-red-500 text-white text-xs font-bold rounded-xl shadow-md active:scale-90 transition-transform">
          <PlusCircle className="w-3.5 h-3.5" /> Add Expense
        </button>
      </div>

      {/* ====== BOARD 1: FEES - EXPENSES ====== */}
      <div className="bg-white rounded-2xl p-4 card-shadow border-t-4 border-emerald-400">
        <div className="flex items-center gap-2 mb-3">
          <div className="w-8 h-8 bg-emerald-100 rounded-lg flex items-center justify-center">
            <Receipt className="w-4 h-4 text-emerald-600" />
          </div>
          <h3 className="text-sm font-bold text-gray-900">Fees Profit</h3>
          <span className="ml-auto text-[10px] text-gray-400">Fees - Expenses</span>
        </div>

        <div className="grid grid-cols-3 gap-3 mb-3">
          <div className="bg-emerald-50 rounded-xl p-3 text-center">
            <p className="text-[10px] text-emerald-600 font-medium uppercase">Fee Revenue</p>
            <p className="text-base font-bold text-emerald-700">{formatCurrency(totalFeeRevenue)}</p>
          </div>
          <div className="bg-red-50 rounded-xl p-3 text-center">
            <p className="text-[10px] text-red-500 font-medium uppercase">Expenses</p>
            <p className="text-base font-bold text-red-600">-{formatCurrency(totalExpenses)}</p>
          </div>
          <div className={`${feeProfit >= 0 ? 'bg-emerald-100' : 'bg-red-100'} rounded-xl p-3 text-center`}>
            <p className={`text-[10px] font-medium uppercase ${feeProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>Fee Profit</p>
            <p className={`text-base font-bold ${feeProfit >= 0 ? 'text-emerald-700' : 'text-red-700'}`}>{feeProfit >= 0 ? '' : '-'}{formatCurrency(Math.abs(feeProfit))}</p>
          </div>
        </div>

        {/* Expense breakdown */}
        {expenseBreakdown.length > 0 && (
          <div className="mt-2 pt-3 border-t border-gray-100">
            <p className="text-[10px] text-gray-400 mb-2 uppercase font-medium">Expense Breakdown</p>
            <div className="space-y-1.5">
              {expenseBreakdown.map(([cat, amt]) => (
                <div key={cat} className="flex items-center gap-2">
                  <span className="text-[11px] text-gray-500 w-24">{catLabels[cat] || cat}</span>
                  <div className="flex-1 h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-red-400 rounded-full" style={{ width: `${Math.min((amt / totalExpenses) * 100, 100)}%` }} />
                  </div>
                  <span className="text-[11px] font-mono font-bold text-gray-700 w-16 text-right">{formatCurrency(amt)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* ====== BOARD 2: EQUIPMENT ====== */}
      <div className="bg-white rounded-2xl p-4 card-shadow border-t-4 border-blue-400">
        <div className="flex items-center gap-2 mb-3">
          <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
            <Package className="w-4 h-4 text-blue-600" />
          </div>
          <h3 className="text-sm font-bold text-gray-900">Equipment</h3>
        </div>

        <div className="grid grid-cols-3 gap-3 mb-3">
          <div className="bg-amber-50 rounded-xl p-3 text-center">
            <p className="text-[10px] text-amber-600 font-medium uppercase">Total Buy</p>
            <p className="text-base font-bold text-amber-700">{formatCurrency(totalEquipmentBuy)}</p>
          </div>
          <div className="bg-blue-50 rounded-xl p-3 text-center">
            <p className="text-[10px] text-blue-600 font-medium uppercase">Sell Revenue</p>
            <p className="text-base font-bold text-blue-700">{formatCurrency(totalEquipmentRevenue)}</p>
          </div>
          <div className={`${equipmentProfit >= 0 ? 'bg-emerald-100' : 'bg-red-100'} rounded-xl p-3 text-center`}>
            <p className={`text-[10px] font-medium uppercase ${equipmentProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>Equip. Profit</p>
            <p className={`text-base font-bold ${equipmentProfit >= 0 ? 'text-emerald-700' : 'text-red-700'}`}>{equipmentProfit >= 0 ? '' : '-'}{formatCurrency(Math.abs(equipmentProfit))}</p>
          </div>
        </div>

        {/* Recent equipment transactions */}
        <div className="mt-2 pt-3 border-t border-gray-100">
          <p className="text-[10px] text-gray-400 mb-2 uppercase font-medium">Recent Transactions</p>
          <div className="space-y-2 max-h-32 overflow-y-auto">
            {transactions.slice(0, 5).map(t => (
              <div key={t.id} className="flex items-center justify-between py-1">
                <div className="flex items-center gap-2">
                  <span className={`px-1.5 py-0.5 text-[9px] font-bold rounded ${t.type === 'sell' ? 'bg-emerald-100 text-emerald-600' : 'bg-amber-100 text-amber-600'}`}>
                    {t.type === 'sell' ? 'SELL' : 'BUY'}
                  </span>
                  <span className="text-[11px] text-gray-700 truncate max-w-[120px]">{t.equipmentName}</span>
                </div>
                <div className="text-right">
                  <span className="text-[11px] font-mono font-bold text-gray-800">{formatCurrency(t.totalAmount)}</span>
                  {t.profit && t.profit > 0 && (
                    <span className="text-[9px] text-emerald-500 ml-1">+{formatCurrency(t.profit)}</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ====== BOARD 3: TOTAL PROFIT (COMBINED) ====== */}
      <div className={`rounded-2xl p-4 card-shadow border-t-4 ${totalProfit >= 0 ? 'border-emerald-400' : 'border-red-400'}`}>
        <div className="flex items-center gap-2 mb-3">
          <div className={`w-8 h-8 ${totalProfit >= 0 ? 'bg-emerald-100' : 'bg-red-100'} rounded-lg flex items-center justify-center`}>
            <Wallet className={`w-4 h-4 ${totalProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`} />
          </div>
          <h3 className="text-sm font-bold text-gray-900">Total Profit</h3>
          <span className="ml-auto text-[10px] text-gray-400">Fees + Equipment</span>
        </div>

        {/* Formula visual */}
        <div className="flex items-center justify-center gap-2 mb-4 py-3 bg-gray-50 rounded-xl">
          <div className="text-center">
            <p className="text-[10px] text-gray-400">Fee Profit</p>
            <p className={`text-sm font-bold ${feeProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>{formatCurrency(feeProfit)}</p>
          </div>
          <span className="text-lg text-gray-300 font-light">+</span>
          <div className="text-center">
            <p className="text-[10px] text-gray-400">Equip. Profit</p>
            <p className={`text-sm font-bold ${equipmentProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>{formatCurrency(equipmentProfit)}</p>
          </div>
          <ArrowRight className="w-4 h-4 text-gray-300" />
          <div className="text-center">
            <p className="text-[10px] text-gray-400">Total</p>
            <p className={`text-sm font-bold ${totalProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>{formatCurrency(totalProfit)}</p>
          </div>
        </div>

        {/* Big total */}
        <div className={`text-center py-4 rounded-xl ${totalProfit >= 0 ? 'bg-emerald-50' : 'bg-red-50'}`}>
          <p className={`text-[10px] uppercase font-medium ${totalProfit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>Net Profit</p>
          <p className={`text-3xl font-extrabold mt-1 ${totalProfit >= 0 ? 'text-emerald-700' : 'text-red-700'}`}>
            {totalProfit >= 0 ? '' : '-'}{formatCurrency(Math.abs(totalProfit))}
          </p>
          {totalProfit >= 0 ? (
            <div className="flex items-center justify-center gap-1 mt-1">
              <TrendingUp className="w-3 h-3 text-emerald-500" />
              <span className="text-[10px] text-emerald-600">Profitable</span>
            </div>
          ) : (
            <div className="flex items-center justify-center gap-1 mt-1">
              <TrendingDown className="w-3 h-3 text-red-500" />
              <span className="text-[10px] text-red-600">Loss</span>
            </div>
          )}
        </div>
      </div>

      {/* ====== BOARD 4: TOTAL REVENUE SUMMARY ====== */}
      <div className="bg-white rounded-2xl p-4 card-shadow border-t-4 border-purple-400">
        <div className="flex items-center gap-2 mb-3">
          <div className="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
            <IndianRupee className="w-4 h-4 text-purple-600" />
          </div>
          <h3 className="text-sm font-bold text-gray-900">Total Revenue Summary</h3>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="bg-emerald-50 rounded-xl p-3">
            <p className="text-[10px] text-emerald-600 font-medium uppercase">Fee Revenue</p>
            <p className="text-lg font-bold text-emerald-700">{formatCurrency(totalFeeRevenue)}</p>
          </div>
          <div className="bg-blue-50 rounded-xl p-3">
            <p className="text-[10px] text-blue-600 font-medium uppercase">Equip. Revenue</p>
            <p className="text-lg font-bold text-blue-700">{formatCurrency(totalEquipmentRevenue)}</p>
          </div>
        </div>
        <div className="mt-3 p-3 bg-purple-50 rounded-xl text-center">
          <p className="text-[10px] text-purple-600 font-medium uppercase">Total Revenue (Fees + Equipment)</p>
          <p className="text-2xl font-extrabold text-purple-700">{formatCurrency(totalRevenue)}</p>
        </div>
      </div>
    </div>
  );
}
