'use client';

import React, { useState } from 'react';
import AppLayout from '@/components/AppLayout';
import { Plus, TrendingUp, TrendingDown, Wallet, DollarSign, ArrowUpRight, ArrowDownRight } from 'lucide-react';

interface Transaction {
  id: string;
  date: string;
  description: string;
  category: string;
  type: 'income' | 'expense';
  amount: number;
  reference: string;
}

const transactions: Transaction[] = [
  { id: 'T001', date: '2026-08-07', description: 'Daily Sales Revenue', category: 'Sales', type: 'income', amount: 95200, reference: 'SALES-20260807' },
  { id: 'T002', date: '2026-08-07', description: 'Staff Salaries — August', category: 'Payroll', type: 'expense', amount: 45000, reference: 'PAY-2026-08' },
  { id: 'T003', date: '2026-08-06', description: 'Daily Sales Revenue', category: 'Sales', type: 'income', amount: 78600, reference: 'SALES-20260806' },
  { id: 'T004', date: '2026-08-06', description: 'Electricity Bill', category: 'Utilities', type: 'expense', amount: 8500, reference: 'UTIL-2026-08' },
  { id: 'T005', date: '2026-08-05', description: 'Purchase Payment — Unga Group', category: 'Purchases', type: 'expense', amount: 48500, reference: 'PO-2026-089' },
  { id: 'T006', date: '2026-08-05', description: 'Daily Sales Revenue', category: 'Sales', type: 'income', amount: 61400, reference: 'SALES-20260805' },
  { id: 'T007', date: '2026-08-04', description: 'Rent — Westlands Branch', category: 'Rent', type: 'expense', amount: 35000, reference: 'RENT-2026-08' },
  { id: 'T008', date: '2026-08-04', description: 'Daily Sales Revenue', category: 'Sales', type: 'income', amount: 52800, reference: 'SALES-20260804' },
];

const expenseCategories = [
  { name: 'Purchases', amount: 48500, color: 'bg-primary' },
  { name: 'Payroll', amount: 45000, color: 'bg-accent' },
  { name: 'Rent', amount: 35000, color: 'bg-info' },
  { name: 'Utilities', amount: 8500, color: 'bg-warning' },
];

export default function FinancePage() {
  const [showModal, setShowModal] = useState(false);
  const [activeTab, setActiveTab] = useState<'cashbook' | 'expenses'>('cashbook');

  const totalIncome = transactions.filter((t) => t.type === 'income').reduce((s, t) => s + t.amount, 0);
  const totalExpenses = transactions.filter((t) => t.type === 'expense').reduce((s, t) => s + t.amount, 0);
  const netBalance = totalIncome - totalExpenses;
  const totalExpCat = expenseCategories.reduce((s, e) => s + e.amount, 0);

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Finance</h1>
            <p className="text-sm text-muted-foreground mt-0.5">Cashbook, expenses, income and financial overview</p>
          </div>
          <button onClick={() => setShowModal(true)} className="btn-primary flex items-center gap-2 px-4 py-2 rounded-md text-sm font-600 text-white">
            <Plus size={16} />
            Record Transaction
          </button>
        </div>

        {/* KPI Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="card-elevated rounded-xl p-5">
            <div className="flex items-center justify-between mb-3">
              <div className="w-9 h-9 rounded-lg bg-success-bg flex items-center justify-center">
                <TrendingUp size={18} className="text-success" />
              </div>
              <ArrowUpRight size={16} className="text-success" />
            </div>
            <p className="text-2xl font-700 text-foreground">KES {totalIncome.toLocaleString()}</p>
            <p className="text-xs text-muted-foreground mt-1">Total Income — This Week</p>
          </div>
          <div className="card-elevated rounded-xl p-5">
            <div className="flex items-center justify-between mb-3">
              <div className="w-9 h-9 rounded-lg bg-danger-bg flex items-center justify-center">
                <TrendingDown size={18} className="text-danger" />
              </div>
              <ArrowDownRight size={16} className="text-danger" />
            </div>
            <p className="text-2xl font-700 text-foreground">KES {totalExpenses.toLocaleString()}</p>
            <p className="text-xs text-muted-foreground mt-1">Total Expenses — This Week</p>
          </div>
          <div className={`card-elevated rounded-xl p-5 ${netBalance >= 0 ? 'border-success/30' : 'border-danger/30'}`}>
            <div className="flex items-center justify-between mb-3">
              <div className={`w-9 h-9 rounded-lg flex items-center justify-center ${netBalance >= 0 ? 'bg-primary/10' : 'bg-danger-bg'}`}>
                <Wallet size={18} className={netBalance >= 0 ? 'text-primary' : 'text-danger'} />
              </div>
              <DollarSign size={16} className={netBalance >= 0 ? 'text-primary' : 'text-danger'} />
            </div>
            <p className={`text-2xl font-700 ${netBalance >= 0 ? 'text-foreground' : 'text-danger'}`}>KES {netBalance.toLocaleString()}</p>
            <p className="text-xs text-muted-foreground mt-1">Net Balance — This Week</p>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 bg-muted rounded-lg p-1 w-fit">
          {(['cashbook', 'expenses'] as const).map((tab) => (
            <button key={tab} onClick={() => setActiveTab(tab)} className={`px-4 py-1.5 rounded-md text-sm font-600 transition-all ${activeTab === tab ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}>
              {tab === 'cashbook' ? 'Cashbook' : 'Expense Breakdown'}
            </button>
          ))}
        </div>

        {activeTab === 'cashbook' && (
          <div className="card-elevated rounded-xl overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-muted/50 border-b border-border">
                    <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Date</th>
                    <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Description</th>
                    <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Category</th>
                    <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Reference</th>
                    <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Type</th>
                    <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Amount (KES)</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {transactions.map((t) => (
                    <tr key={t.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 text-xs text-muted-foreground">{t.date}</td>
                      <td className="px-4 py-3 font-600 text-foreground">{t.description}</td>
                      <td className="px-4 py-3 text-sm text-muted-foreground">{t.category}</td>
                      <td className="px-4 py-3 text-xs font-mono text-primary">{t.reference}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-600 ${t.type === 'income' ? 'badge-success' : 'badge-danger'}`}>
                          {t.type === 'income' ? 'Income' : 'Expense'}
                        </span>
                      </td>
                      <td className={`px-4 py-3 text-right font-tabular font-700 ${t.type === 'income' ? 'text-success' : 'text-danger'}`}>
                        {t.type === 'income' ? '+' : '-'}{t.amount.toLocaleString()}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {activeTab === 'expenses' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {expenseCategories.map((cat) => (
              <div key={cat.name} className="card-elevated rounded-xl p-5">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="font-700 text-foreground">{cat.name}</h3>
                  <span className="text-sm font-700 text-foreground">KES {cat.amount.toLocaleString()}</span>
                </div>
                <div className="w-full bg-muted rounded-full h-2">
                  <div className={`h-2 rounded-full ${cat.color}`} style={{ width: `${(cat.amount / totalExpCat) * 100}%` }} />
                </div>
                <p className="text-xs text-muted-foreground mt-1.5">{((cat.amount / totalExpCat) * 100).toFixed(1)}% of total expenses</p>
              </div>
            ))}
          </div>
        )}

        {showModal && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
            <div className="bg-card rounded-xl shadow-xl w-full max-w-md p-6 fade-in">
              <div className="flex items-center justify-between mb-5">
                <h2 className="text-base font-700 text-foreground">Record Transaction</h2>
                <button onClick={() => setShowModal(false)} className="p-1.5 rounded hover:bg-muted text-muted-foreground">✕</button>
              </div>
              <div className="space-y-4">
                {[{ label: 'Type', placeholder: 'Income / Expense' }, { label: 'Description', placeholder: 'Transaction description' }, { label: 'Category', placeholder: 'Sales / Rent / Utilities…' }, { label: 'Amount (KES)', placeholder: '0.00' }, { label: 'Date', placeholder: 'YYYY-MM-DD' }, { label: 'Reference', placeholder: 'Reference number' }].map((f) => (
                  <div key={f.label}>
                    <label className="block text-xs font-600 text-foreground mb-1">{f.label}</label>
                    <input placeholder={f.placeholder} className="w-full h-9 px-3 text-sm bg-background border border-border rounded-md outline-none focus:border-primary text-foreground placeholder:text-muted-foreground" />
                  </div>
                ))}
              </div>
              <div className="flex gap-3 mt-6">
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted">Cancel</button>
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md btn-primary text-sm font-600 text-white">Save Transaction</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
