import React, { useState, useMemo } from 'react';
import { 
  Landmark, 
  FileCheck, 
  Calculator, 
  History, 
  AlertTriangle, 
  Download, 
  Calendar,
  ArrowRight,
  ShieldCheck,
  Percent,
  Info,
  Plus,
  X,
  Search,
  Filter,
  Trash2
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { useApp } from '@/context/AppContext';

interface TaxFiling {
  id: string;
  type: 'VAT' | 'Corporate' | 'Payroll' | 'Income';
  period: string;
  dueDate: string;
  amount: number;
  status: 'Draft' | 'Filed' | 'Paid' | 'Overdue';
}

export function TaxModule() {
  const { projects, expenses, companySettings, updateCompanySettings } = useApp();
  const [activeTab, setActiveTab] = useState<'overview' | 'filings' | 'calculator'>('overview');
  const [isFilingModalOpen, setIsFilingModalOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterType, setFilterType] = useState('All');
  const [filterStatus, setFilterStatus] = useState('All');
  const filterRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (filterRef.current && !filterRef.current.contains(event.target as Node)) {
        setIsFilterOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const [newFiling, setNewFiling] = useState<Partial<TaxFiling>>({
    type: 'VAT',
    period: '',
    dueDate: '',
    amount: 0,
    status: 'Draft'
  });

  // Tax Filings State (Manual entries)
  const [filings, setFilings] = useState<TaxFiling[]>([]);

  const handleAddFiling = (e: React.FormEvent) => {
    e.preventDefault();
    const id = `TAX-${new Date().getFullYear()}-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
    const filing: TaxFiling = {
      id,
      type: newFiling.type as any,
      period: newFiling.period || '',
      dueDate: newFiling.dueDate || '',
      amount: Number(newFiling.amount) || 0,
      status: newFiling.status as any
    };
    setFilings([filing, ...filings]);
    setIsFilingModalOpen(false);
    setNewFiling({ type: 'VAT', period: '', dueDate: '', amount: 0, status: 'Draft' });
    toast.success('Tax filing record added successfully');
  };

  const updateFilingStatus = (id: string, newStatus: TaxFiling['status']) => {
    setFilings(filings.map(f => f.id === id ? { ...f, status: newStatus } : f));
    toast.success(`Filing status updated to ${newStatus}`);
  };

  const handleDeleteFiling = (id: string) => {
    if (id.includes('-CUR')) {
      toast.error('Cannot delete live data projections. These are calculated from active projects.');
      return;
    }
    setFilings(filings.filter(f => f.id !== id));
    toast.success('Tax filing record deleted');
  };

  // Calculate Tax Estimates based on real data
  const taxEstimates = useMemo(() => {
    let totalRevenue = 0;
    let totalExpenses = 0;
    let actualTaxPayable = 0;
    let totalTaxPaid = 0;

    projects.forEach(p => {
      totalRevenue += p.clientTotalAmount || 0;
      totalExpenses += p.totalAmount || 0;
      actualTaxPayable += p.taxAmount || 0;
    });

    expenses.forEach(e => {
      if (e.status === 'Approved') {
        if (e.category === 'Tax Payment') {
          totalTaxPaid += e.amount;
        } else {
          totalExpenses += e.amount;
        }
      }
    });

    const netProfit = totalRevenue - totalExpenses - totalTaxPaid;
    const vatRate = (companySettings.vatTaxRate || 20) / 100;
    const corporateTaxRate = (companySettings.corporateTaxRate || 25) / 100;

    return {
      estimatedVAT: actualTaxPayable - totalTaxPaid,
      estimatedCorporateTax: Math.max(0, netProfit * corporateTaxRate),
      netProfit,
      totalRevenue,
      totalExpenses,
      totalTaxPaid,
      actualTaxPayable
    };
  }, [projects, expenses]);

  // Inject live data into filings
  const liveFilings = useMemo(() => {
    const manualFilings = [...filings];
    const autoFilings: TaxFiling[] = [];
    
    // Group projects by period (Quarter)
    const periodMap = new Map<string, { vat: number, corp: number, dueDate: string }>();
    
    projects.forEach(p => {
      if (!p.issueDate) return;
      const date = new Date(p.issueDate);
      const year = date.getFullYear();
      const quarter = Math.floor(date.getMonth() / 3) + 1;
      const period = `Q${quarter} ${year}`;
      
      const existing = periodMap.get(period) || { 
        vat: 0, 
        corp: 0, 
        dueDate: `${year}-${(quarter * 3).toString().padStart(2, '0')}-30` 
      };
      
      periodMap.set(period, {
        ...existing,
        vat: existing.vat + (p.taxAmount || 0),
        corp: existing.corp + ((p.clientTotalAmount || 0) * ((companySettings.corporateTaxRate || 25) / 100))
      });
    });

    periodMap.forEach((data, period) => {
      if (data.vat > 0) {
        const isPaid = expenses.some(e => 
          e.category === 'Tax Payment' && 
          e.status === 'Approved' &&
          (e.description.toLowerCase().includes(period.toLowerCase()) || e.description.toLowerCase().includes('vat'))
        );
        
        autoFilings.push({
          id: `LIVE-VAT-${period.replace(' ', '-')}`,
          type: 'VAT',
          period,
          dueDate: data.dueDate,
          amount: data.vat,
          status: isPaid ? 'Paid' : 'Draft'
        });
      }
      
      if (data.corp > 0) {
        const isPaid = expenses.some(e => 
          e.category === 'Tax Payment' && 
          e.status === 'Approved' &&
          (e.description.toLowerCase().includes(period.toLowerCase()) || e.description.toLowerCase().includes('corporate'))
        );

        autoFilings.push({
          id: `LIVE-CORP-${period.replace(' ', '-')}`,
          type: 'Corporate',
          period,
          dueDate: data.dueDate,
          amount: data.corp,
          status: isPaid ? 'Paid' : 'Draft'
        });
      }
    });

    // Sort by period descending
    return [...manualFilings, ...autoFilings].sort((a, b) => {
      const aYear = parseInt(a.period.split(' ').pop() || '0');
      const bYear = parseInt(b.period.split(' ').pop() || '0');
      if (aYear !== bYear) return bYear - aYear;
      return b.period.localeCompare(a.period);
    });
  }, [filings, projects, expenses]);

  const filteredFilings = useMemo(() => {
    return liveFilings.filter(f => {
      const matchesSearch = f.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
        f.period.toLowerCase().includes(searchQuery.toLowerCase()) ||
        f.type.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesType = filterType === 'All' || f.type === filterType;
      const matchesStatus = filterStatus === 'All' || f.status === filterStatus;
      
      return matchesSearch && matchesType && matchesStatus;
    });
  }, [liveFilings, searchQuery, filterType, filterStatus]);

  // Calculator State
  const [calcRevenue, setCalcRevenue] = useState(0);
  const [calcExpenses, setCalcExpenses] = useState(0);
  const [calcCorpRate, setCalcCorpRate] = useState(companySettings.corporateTaxRate || 25);
  const [calcVatRate, setCalcVatRate] = useState(companySettings.vatTaxRate || 20);
  const [customEstimates, setCustomEstimates] = useState({
    corpTax: 0,
    vatTax: 0,
    total: 0
  });

  // Initialize calculator with real data only once or when reset
  const [isCalculatedInitialized, setIsCalculatedInitialized] = useState(false);

  React.useEffect(() => {
    if (!isCalculatedInitialized) {
      setCalcRevenue(taxEstimates.totalRevenue);
      setCalcExpenses(taxEstimates.totalExpenses);
      setCalcCorpRate(companySettings.corporateTaxRate || 25);
      setCalcVatRate(companySettings.vatTaxRate || 20);
      setIsCalculatedInitialized(true);
    }
    
    // Always update custom estimates when revenue/expenses/rates change
    const profit = calcRevenue - calcExpenses;
    const corpTax = Math.max(0, profit * (calcCorpRate / 100));
    const vatTax = calcRevenue * (calcVatRate / 100);
    
    setCustomEstimates({
      corpTax,
      vatTax,
      total: corpTax + vatTax
    });
  }, [taxEstimates.totalRevenue, taxEstimates.totalExpenses, companySettings.corporateTaxRate, companySettings.vatTaxRate, isCalculatedInitialized, calcRevenue, calcExpenses, calcCorpRate, calcVatRate]);

  const handleRecalculate = () => {
    const profit = calcRevenue - calcExpenses;
    const corpTax = Math.max(0, profit * (calcCorpRate / 100));
    const vatTax = calcRevenue * (calcVatRate / 100); // Simplified VAT for calculator
    
    setCustomEstimates({
      corpTax,
      vatTax,
      total: corpTax + vatTax
    });
    toast.success('Tax estimates recalculated');
  };

  const handleSaveDefaultRates = () => {
    updateCompanySettings({
      corporateTaxRate: calcCorpRate,
      vatTaxRate: calcVatRate
    });
    toast.success('Default system tax rates updated successfully');
  };

  const handleExportCSV = () => {
    if (filteredFilings.length === 0) {
      toast.error('No data to export');
      return;
    }

    const headers = ['Filing ID', 'Tax Type', 'Period', 'Due Date', 'Amount', 'Status'];
    const csvRows = [
      headers.join(','),
      ...filteredFilings.map(f => [
        `"${f.id}"`,
        `"${f.type}"`,
        `"${f.period}"`,
        `"${f.dueDate}"`,
        f.amount.toFixed(2),
        `"${f.status}"`
      ].join(','))
    ];

    const csvContent = csvRows.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `tax_filings_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    toast.success('Tax data exported successfully');
  };

  const handleRecordPayment = () => {
    toast.info('To record a tax payment, please add an expense with category "Tax Payment"');
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-500">
            <Landmark size={24} />
          </div>
          <div>
            <h2 className="text-2xl font-bold tracking-tight">Government Tax Module</h2>
            <p className="text-sm text-muted-foreground">Manage compliance, filings, and tax obligations.</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button 
            onClick={() => setIsFilingModalOpen(true)}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Plus size={18} />
            New Tax Filing
          </button>
          <button 
            onClick={handleExportCSV}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Download size={18} />
            Export Tax Data
          </button>
          <button 
            onClick={handleRecordPayment}
            className="flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-bold text-white hover:bg-indigo-700 transition-all shadow-md active:scale-95"
          >
            <FileCheck size={18} />
            Record Tax Payment
          </button>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="flex items-center gap-1 p-1 bg-muted/50 rounded-xl border border-border w-fit">
        <button 
          onClick={() => setActiveTab('overview')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            activeTab === 'overview' ? "bg-card shadow-sm text-indigo-600" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <Landmark size={16} />
          Tax Overview
        </button>
        <button 
          onClick={() => setActiveTab('filings')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            activeTab === 'filings' ? "bg-card shadow-sm text-indigo-600" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <History size={16} />
          Filing History
        </button>
        <button 
          onClick={() => setActiveTab('calculator')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            activeTab === 'calculator' ? "bg-card shadow-sm text-indigo-600" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <Calculator size={16} />
          Tax Calculator
        </button>
      </div>

      <AnimatePresence mode="wait">
        {activeTab === 'overview' && (
          <motion.div
            key="overview"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-6"
          >
            {/* Tax KPI Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <TaxCard 
                title="Current VAT Payable" 
                amount={taxEstimates.estimatedVAT} 
                description={`Total Accrued: $${taxEstimates.actualTaxPayable.toLocaleString()}`}
                icon={Percent}
                color="blue"
              />
              <TaxCard 
                title="Tax Paid to Date" 
                amount={taxEstimates.totalTaxPaid} 
                description="Current Fiscal Year"
                icon={ShieldCheck}
                color="green"
              />
              <TaxCard 
                title="Corporate Tax Provision" 
                amount={taxEstimates.estimatedCorporateTax} 
                description="Estimated on Net Profit"
                icon={Calculator}
                color="indigo"
              />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Compliance Status */}
              <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-lg font-bold">Compliance Status</h3>
                  <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-green-500/10 text-green-500 uppercase tracking-wider">
                    <ShieldCheck size={14} />
                    Fully Compliant
                  </span>
                </div>
                <div className="space-y-4">
                  <ComplianceItem 
                    label="VAT Registration" 
                    status="Verified" 
                    lastChecked="2 days ago"
                  />
                  <ComplianceItem 
                    label="Tax ID (EIN/VAT)" 
                    status="Active" 
                    lastChecked="1 month ago"
                  />
                  <ComplianceItem 
                    label="Annual Return" 
                    status="Up to Date" 
                    lastChecked="FY 2025 Filed"
                  />
                </div>
              </div>

              {/* Tax Alerts */}
              <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
                <h3 className="text-lg font-bold mb-6">Tax Alerts & Reminders</h3>
                <div className="space-y-4">
                  <div className="flex gap-4 p-4 rounded-xl bg-orange-500/5 border border-orange-500/20">
                    <div className="p-2 rounded-lg bg-orange-500/10 text-orange-500 h-fit">
                      <AlertTriangle size={20} />
                    </div>
                    <div>
                      <h4 className="font-bold text-orange-700">Upcoming Deadline</h4>
                      <p className="text-sm text-orange-600/80">Payroll tax filing for March 2026 is due in 4 days. Please review and submit.</p>
                    </div>
                  </div>
                  <div className="flex gap-4 p-4 rounded-xl bg-blue-500/5 border border-blue-500/20">
                    <div className="p-2 rounded-lg bg-blue-500/10 text-blue-500 h-fit">
                      <Info size={20} />
                    </div>
                    <div>
                      <h4 className="font-bold text-blue-700">New Tax Regulation</h4>
                      <p className="text-sm text-blue-600/80">Updated corporate tax rates for 2026 have been applied to your estimates.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
        )}

        {activeTab === 'filings' && (
          <motion.div
            key="filings"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-4"
          >
            {/* Filters & Search */}
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between">
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
                <input
                  type="text"
                  placeholder="Search filings, periods..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="relative" ref={filterRef}>
                <button 
                  onClick={() => setIsFilterOpen(!isFilterOpen)}
                  className={cn(
                    "flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-accent",
                    (filterType !== 'All' || filterStatus !== 'All') && "border-primary text-primary"
                  )}
                >
                  <Filter size={18} />
                  Filters
                  {(filterType !== 'All' || filterStatus !== 'All') && (
                    <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                      {[filterType, filterStatus].filter(f => f !== 'All').length}
                    </span>
                  )}
                </button>

                {isFilterOpen && (
                  <div className="absolute right-0 mt-2 z-50 w-64 rounded-xl border border-border bg-card p-4 shadow-lg animate-in fade-in slide-in-from-top-2 duration-200">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="font-bold text-sm">Filter Filings</h4>
                      <button 
                        onClick={() => {
                          setFilterType('All');
                          setFilterStatus('All');
                        }}
                        className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
                      >
                        Reset
                      </button>
                    </div>
                    
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Tax Type</label>
                        <select 
                          value={filterType}
                          onChange={(e) => setFilterType(e.target.value)}
                          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        >
                          <option value="All">All Types</option>
                          <option value="VAT">VAT</option>
                          <option value="Corporate">Corporate</option>
                          <option value="Payroll">Payroll</option>
                          <option value="Income">Income</option>
                        </select>
                      </div>

                      <div className="space-y-2">
                        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Status</label>
                        <select 
                          value={filterStatus}
                          onChange={(e) => setFilterStatus(e.target.value)}
                          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        >
                          <option value="All">All Statuses</option>
                          <option value="Draft">Draft</option>
                          <option value="Filed">Filed</option>
                          <option value="Paid">Paid</option>
                          <option value="Overdue">Overdue</option>
                        </select>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
              <table className="w-full text-left text-sm">
                <thead className="bg-muted/50 border-b border-border">
                  <tr>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Filing ID</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Tax Type</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Period</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Due Date</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground text-right">Amount</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Status</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground text-right">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredFilings.map((filing) => (
                    <tr key={filing.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 font-mono text-xs">{filing.id}</td>
                      <td className="px-4 py-3">
                        <span className="font-medium">{filing.type} Tax</span>
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">{filing.period}</td>
                      <td className="px-4 py-3 text-muted-foreground">{filing.dueDate}</td>
                      <td className="px-4 py-3 text-right font-mono font-bold">
                        ${filing.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <span className={cn(
                            "inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider",
                            filing.status === 'Paid' ? "bg-green-500/10 text-green-500" :
                            filing.status === 'Filed' ? "bg-indigo-500/10 text-indigo-500" :
                            filing.status === 'Draft' ? "bg-blue-500/10 text-blue-500" :
                            "bg-red-500/10 text-red-500"
                          )}>
                            {filing.status}
                          </span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          {filing.status === 'Draft' && (
                            <button 
                              onClick={() => updateFilingStatus(filing.id, 'Filed')}
                              className="text-[10px] font-bold text-indigo-600 hover:underline"
                            >
                              MARK AS FILED
                            </button>
                          )}
                          {filing.status === 'Filed' && (
                            <button 
                              onClick={() => updateFilingStatus(filing.id, 'Paid')}
                              className="text-[10px] font-bold text-green-600 hover:underline"
                            >
                              MARK AS PAID
                            </button>
                          )}
                          {!filing.id.includes('-CUR') && (
                            <button 
                              onClick={() => handleDeleteFiling(filing.id)}
                              className="p-1.5 rounded-lg text-muted-foreground hover:bg-red-500/10 hover:text-red-500 transition-colors"
                              title="Delete Filing"
                            >
                              <Trash2 size={14} />
                            </button>
                          )}
                          <button className="text-muted-foreground hover:text-foreground">
                            <ArrowRight size={14} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </motion.div>
        )}

        {activeTab === 'calculator' && (
          <motion.div
            key="calculator"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="grid grid-cols-1 lg:grid-cols-3 gap-6"
          >
            <div className="lg:col-span-2 space-y-6">
              <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
                <h3 className="text-lg font-bold mb-6">Interactive Tax Calculator</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Annual Revenue ($)</label>
                    <input 
                      type="number" 
                      value={calcRevenue}
                      onChange={(e) => setCalcRevenue(Number(e.target.value))}
                      className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Annual Expenses ($)</label>
                    <input 
                      type="number" 
                      value={calcExpenses}
                      onChange={(e) => setCalcExpenses(Number(e.target.value))}
                      className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Corporate Tax Rate (%)</label>
                    <input 
                      type="number" 
                      value={calcCorpRate}
                      onChange={(e) => setCalcCorpRate(Number(e.target.value))}
                      className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">VAT/Sales Tax Rate (%)</label>
                    <input 
                      type="number" 
                      value={calcVatRate}
                      onChange={(e) => setCalcVatRate(Number(e.target.value))}
                      className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
                    />
                  </div>
                </div>
                <div className="mt-8 pt-6 border-t border-border flex items-center justify-between">
                  <p className="text-xs text-muted-foreground flex items-center gap-1">
                    <Info size={14} />
                    Changes here are for calculation only unless saved as default.
                  </p>
                  <div className="flex items-center gap-3">
                    <button 
                      onClick={handleSaveDefaultRates}
                      className="text-indigo-600 px-4 py-2 rounded-lg font-bold hover:bg-indigo-50 transition-all text-sm"
                    >
                      Save as Default System Rates
                    </button>
                    <button 
                      onClick={handleRecalculate}
                      className="bg-indigo-600 text-white px-6 py-2 rounded-lg font-bold hover:bg-indigo-700 transition-all active:scale-95 shadow-md flex items-center gap-2"
                    >
                      <Calculator size={18} />
                      Recalculate Projections
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div className="space-y-6">
              <div className="rounded-2xl border border-border bg-indigo-600 p-6 text-white shadow-lg shadow-indigo-200">
                <h3 className="text-lg font-bold mb-2">Estimated Liability</h3>
                <p className="text-indigo-100 text-sm mb-6">Total projected tax obligation based on calculator inputs.</p>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-indigo-200 text-sm">Corporate Tax</span>
                    <span className="text-xl font-bold">${customEstimates.corpTax.toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-indigo-200 text-sm">VAT (Projected)</span>
                    <span className="text-xl font-bold">${customEstimates.vatTax.toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>
                  </div>
                  <div className="pt-4 border-t border-indigo-500 flex justify-between items-center">
                    <span className="font-bold">Total Estimate</span>
                    <span className="text-3xl font-bold">${customEstimates.total.toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>
                  </div>
                </div>
              </div>
              
              <button 
                onClick={() => {
                  setCalcRevenue(taxEstimates.totalRevenue);
                  setCalcExpenses(taxEstimates.totalExpenses);
                  setCalcCorpRate(companySettings.corporateTaxRate || 25);
                  setCalcVatRate(companySettings.vatTaxRate || 20);
                  setIsCalculatedInitialized(true); 
                  handleRecalculate();
                  toast.info('Reset to actual business data');
                }}
                className="w-full py-3 rounded-xl border border-dashed border-border text-muted-foreground text-sm font-medium hover:border-indigo-500 hover:text-indigo-600 transition-all"
              >
                Reset to Actual Business Data
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
      
      {/* New Filing Modal */}
      {isFilingModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="bg-indigo-500/5 border-b border-border p-6 flex items-center justify-between">
              <h2 className="text-xl font-bold">New Tax Filing</h2>
              <button 
                onClick={() => setIsFilingModalOpen(false)}
                className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleAddFiling} className="p-6 space-y-4">
              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Tax Type</label>
                <select 
                  value={newFiling.type}
                  onChange={(e) => setNewFiling({...newFiling, type: e.target.value as any})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:bg-background transition-all"
                  required
                >
                  <option value="VAT">VAT Tax</option>
                  <option value="Corporate">Corporate Tax</option>
                  <option value="Payroll">Payroll Tax</option>
                  <option value="Income">Income Tax</option>
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Period</label>
                <input 
                  type="text" 
                  placeholder="e.g. Q2 2026"
                  value={newFiling.period}
                  onChange={(e) => setNewFiling({...newFiling, period: e.target.value})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:bg-background transition-all"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Due Date</label>
                  <input 
                    type="date" 
                    value={newFiling.dueDate}
                    onChange={(e) => setNewFiling({...newFiling, dueDate: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:bg-background transition-all"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Amount ($)</label>
                  <input 
                    type="number" 
                    step="0.01"
                    value={newFiling.amount}
                    onChange={(e) => setNewFiling({...newFiling, amount: parseFloat(e.target.value)})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:bg-background transition-all"
                    required
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Status</label>
                <select 
                  value={newFiling.status}
                  onChange={(e) => setNewFiling({...newFiling, status: e.target.value as any})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:bg-background transition-all"
                  required
                >
                  <option value="Draft">Draft</option>
                  <option value="Filed">Filed</option>
                  <option value="Paid">Paid</option>
                </select>
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => setIsFilingModalOpen(false)}
                  className="flex-1 h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="flex-1 h-11 bg-indigo-600 text-sm font-bold text-white rounded-xl hover:bg-indigo-700 transition-all shadow-md"
                >
                  Add Filing
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

function TaxCard({ title, amount, description, icon: Icon, color, isDate }: { title: string, amount: string | number, description: string, icon: any, color: string, isDate?: boolean }) {
  return (
    <div className="rounded-2xl border border-border bg-card p-6 shadow-sm hover:shadow-md transition-all">
      <div className="flex items-center justify-between mb-4">
        <div className={cn(
          "p-2 rounded-lg",
          color === 'blue' ? "bg-blue-500/10 text-blue-500" :
          color === 'indigo' ? "bg-indigo-500/10 text-indigo-500" :
          color === 'green' ? "bg-green-500/10 text-green-500" :
          "bg-orange-500/10 text-orange-500"
        )}>
          <Icon size={20} />
        </div>
      </div>
      <h3 className="text-sm font-medium text-muted-foreground mb-1">{title}</h3>
      <div className="text-2xl font-bold mb-1">
        {typeof amount === 'number' ? `$${amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}` : amount}
      </div>
      <p className="text-xs text-muted-foreground">{description}</p>
    </div>
  );
}

function ComplianceItem({ label, status, lastChecked }: { label: string, status: string, lastChecked: string }) {
  return (
    <div className="flex items-center justify-between p-3 rounded-xl bg-muted/30 border border-border/50">
      <div>
        <p className="text-sm font-bold">{label}</p>
        <p className="text-[10px] text-muted-foreground uppercase tracking-wider">Last Checked: {lastChecked}</p>
      </div>
      <span className="text-xs font-bold text-green-500">{status}</span>
    </div>
  );
}
