import React, { useState, useEffect } from 'react';
import { TrendingUp, FileText, Download } from 'lucide-react';
import { toast } from 'react-toastify';
import financialReportService, { ProfitLossReport, BalanceSheetReport, TaxReport } from '../../features/payments/services/financialReportService';
import glService from '../../features/payments/services/glService';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';

const FinancialReportsPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [activeTab, setActiveTab] = useState<'pl' | 'balance' | 'tax'>('pl');
  const [loading, setLoading] = useState(false);
  const [plReport, setPlReport] = useState<ProfitLossReport | null>(null);
  const [balanceReport, setBalanceReport] = useState<BalanceSheetReport | null>(null);
  const [taxReport, setTaxReport] = useState<TaxReport | null>(null);
  const [periods, setPeriods] = useState<Array<{ id: number; name: string; start_date: string; end_date: string }>>([]);
  const [selectedPeriod, setSelectedPeriod] = useState<number | null>(null);
  const [dateRange, setDateRange] = useState({
    start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    end: new Date().toISOString().split('T')[0],
  });

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

  useEffect(() => {
    if (activeTab === 'pl') fetchPLReport();
    else if (activeTab === 'balance') fetchBalanceSheet();
    else if (activeTab === 'tax') fetchTaxReport();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, selectedPeriod, dateRange]);

  const fetchPeriods = async () => {
    try {
      const response = await glService.getFiscalPeriods();
      setPeriods(response.data.fiscal_periods || []);
    } catch (error) {
      // Silently fail
    }
  };

  const fetchPLReport = async () => {
    try {
      setLoading(true);
      const params: { fiscal_period_id?: number; start_date?: string; end_date?: string; as_of_date?: string } = {};
      if (selectedPeriod) {
        params.fiscal_period_id = selectedPeriod;
      } else {
        params.start_date = dateRange.start;
        params.end_date = dateRange.end;
      }
      const response = await financialReportService.getProfitLoss(params);
      setPlReport(response.data);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load P&L report');
    } finally {
      setLoading(false);
    }
  };

  const fetchBalanceSheet = async () => {
    try {
      setLoading(true);
      const params: { fiscal_period_id?: number; start_date?: string; end_date?: string; as_of_date?: string } = {};
      if (selectedPeriod) {
        params.fiscal_period_id = selectedPeriod;
      } else {
        params.as_of_date = dateRange.end;
      }
      const response = await financialReportService.getBalanceSheet(params);
      setBalanceReport(response.data);
    } catch (error: unknown) {
      const errorResponse = (error && typeof error === 'object' && 'response' in error && error.response && typeof error.response === 'object' && 'data' in error.response && error.response.data && typeof error.response.data === 'object' && 'detail' in error.response.data && typeof error.response.data.detail === 'string') ? error.response.data.detail : undefined;
      toast.error(errorResponse || 'Failed to load balance sheet');
    } finally {
      setLoading(false);
    }
  };

  const fetchTaxReport = async () => {
    try {
      setLoading(true);
      const params: { start_date: string; end_date: string } = {
        start_date: dateRange.start,
        end_date: dateRange.end,
      };
      const response = await financialReportService.getTaxReport(params);
      if (response && 'data' in response && !(response instanceof Blob)) {
        setTaxReport(response.data);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load tax report');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async (format: 'csv' | 'json') => {
    try {
      const response = await financialReportService.getTaxReport({
        start_date: dateRange.start,
        end_date: dateRange.end,
        format
      });
      if (response instanceof Blob) {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement('a');
        a.href = url;
        a.download = `tax-report-${dateRange.start}-${dateRange.end}.${format}`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        toast.success('Report exported successfully');
      }
    } catch (error: unknown) {
      toast.error('Failed to export report');
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      {/* Header */}
      <div className="mb-6 sm:mb-8 md:mb-10">
        <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
          <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-emerald-400 via-green-500 to-emerald-600 rounded-full"></div>
          <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent">
            Financial Reports
          </h1>
        </div>
        <p className="text-slate-600 text-sm sm:text-base md:text-lg font-light">
          Profit & Loss, Balance Sheet, and Tax Reports
        </p>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-lg p-4 mb-6">
        <div className="flex flex-wrap gap-4 items-end">
          <div className="flex-1 min-w-[200px]">
            <label className="block text-sm font-semibold mb-2">Fiscal Period</label>
            <select
              value={selectedPeriod || ''}
              onChange={(e) => setSelectedPeriod(e.target.value ? parseInt(e.target.value) : null)}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg"
            >
              <option value="">Custom Date Range</option>
              {periods.map((p) => (
                <option key={p.id} value={p.id}>{p.name}</option>
              ))}
            </select>
          </div>
          {!selectedPeriod && (
            <>
              <div className="flex-1 min-w-[150px]">
                <label className="block text-sm font-semibold mb-2">Start Date</label>
                <input
                  type="date"
                  value={dateRange.start}
                  onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
                  className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                />
              </div>
              <div className="flex-1 min-w-[150px]">
                <label className="block text-sm font-semibold mb-2">End Date</label>
                <input
                  type="date"
                  value={dateRange.end}
                  onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
                  className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                />
              </div>
            </>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-6 border-b border-slate-200">
        <button
          onClick={() => setActiveTab('pl')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'pl'
              ? 'bg-emerald-500 text-white border-b-2 border-emerald-600'
              : 'text-slate-600 hover:text-emerald-600'
          }`}
        >
          <TrendingUp className="inline w-4 h-4 mr-2" />
          Profit & Loss
        </button>
        <button
          onClick={() => setActiveTab('balance')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'balance'
              ? 'bg-emerald-500 text-white border-b-2 border-emerald-600'
              : 'text-slate-600 hover:text-emerald-600'
          }`}
        >
          <FileText className="inline w-4 h-4 mr-2" />
          Balance Sheet
        </button>
        <button
          onClick={() => setActiveTab('tax')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'tax'
              ? 'bg-emerald-500 text-white border-b-2 border-emerald-600'
              : 'text-slate-600 hover:text-emerald-600'
          }`}
        >
          <FileText className="inline w-4 h-4 mr-2" />
          Tax Report
        </button>
      </div>

      {/* Content */}
      {loading ? (
        <Loading text="Loading report..." />
      ) : (
        <>
          {activeTab === 'pl' && plReport && (
            <div className="bg-white rounded-xl shadow-lg p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold">Profit & Loss Statement</h2>
                <button
                  onClick={() => handleExport('csv')}
                  className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2"
                >
                  <Download className="w-4 h-4" />
                  Export CSV
                </button>
              </div>
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-3">Revenue</h3>
                  <div className="space-y-2">
                    {plReport.revenue?.revenue_by_account && Object.entries(plReport.revenue.revenue_by_account).map(([account, amount]) => (
                      <div key={account} className="flex justify-between p-2 bg-slate-50 rounded">
                        <span>{account}</span>
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </div>
                    ))}
                    <div className="flex justify-between p-3 bg-emerald-50 rounded border-t-2 border-emerald-500 font-bold">
                      <span>Total Revenue</span>
                      <span>{formatCurrency(plReport.revenue?.total_revenue || 0)}</span>
                    </div>
                  </div>
                </div>
                <div>
                  <h3 className="text-lg font-semibold mb-3">Cost of Goods Sold</h3>
                  <div className="flex justify-between p-3 bg-slate-50 rounded">
                    <span>Total COGS</span>
                    <span className="font-semibold">{formatCurrency(plReport.costs?.total_cogs || 0)}</span>
                  </div>
                  <div className="flex justify-between p-3 bg-blue-50 rounded border-t-2 border-blue-500 font-bold mt-2">
                    <span>Gross Profit</span>
                    <span>{formatCurrency(plReport.costs?.gross_profit || 0)}</span>
                  </div>
                </div>
                <div>
                  <h3 className="text-lg font-semibold mb-3">Operating Expenses</h3>
                  <div className="space-y-2">
                    {plReport.expenses?.expenses_by_account && Object.entries(plReport.expenses.expenses_by_account).map(([account, amount]) => (
                      <div key={account} className="flex justify-between p-2 bg-slate-50 rounded">
                        <span>{account}</span>
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </div>
                    ))}
                    <div className="flex justify-between p-3 bg-slate-100 rounded border-t-2 border-slate-400 font-semibold">
                      <span>Total Operating Expenses</span>
                      <span>{formatCurrency(plReport.expenses?.total_operating_expenses || 0)}</span>
                    </div>
                  </div>
                </div>
                <div className="flex justify-between p-4 bg-gradient-to-r from-emerald-100 to-green-100 rounded border-t-4 border-emerald-500">
                  <span className="text-xl font-bold">Net Profit</span>
                  <span className="text-xl font-bold">{formatCurrency(plReport.profit?.net_profit || 0)}</span>
                </div>
                <div className="text-sm text-slate-600">
                  Profit Margin: {plReport.profit?.profit_margin ? plReport.profit.profit_margin.toFixed(2) : '0.00'}%
                </div>
              </div>
            </div>
          )}

          {activeTab === 'balance' && balanceReport && (
            <div className="bg-white rounded-xl shadow-lg p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold">Balance Sheet</h2>
                <div className="text-sm text-slate-600">
                  As of: {balanceReport.as_of_date ? formatDate(balanceReport.as_of_date) : 'N/A'}
                </div>
              </div>
              <div className="grid md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-lg font-semibold mb-3">Assets</h3>
                  <div className="space-y-2">
                    {balanceReport.assets?.breakdown && Object.entries(balanceReport.assets.breakdown).map(([account, amount]) => (
                      <div key={account} className="flex justify-between p-2 bg-slate-50 rounded">
                        <span>{account}</span>
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </div>
                    ))}
                    <div className="flex justify-between p-3 bg-emerald-50 rounded border-t-2 border-emerald-500 font-bold">
                      <span>Total Assets</span>
                      <span>{formatCurrency(balanceReport.assets?.total_assets || 0)}</span>
                    </div>
                  </div>
                </div>
                <div>
                  <h3 className="text-lg font-semibold mb-3">Liabilities & Equity</h3>
                  <div className="space-y-2">
                    {balanceReport.liabilities?.breakdown && Object.entries(balanceReport.liabilities.breakdown).map(([account, amount]) => (
                      <div key={account} className="flex justify-between p-2 bg-slate-50 rounded">
                        <span>{account}</span>
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </div>
                    ))}
                    <div className="flex justify-between p-3 bg-slate-100 rounded border-t-2 border-slate-400 font-semibold">
                      <span>Total Liabilities</span>
                      <span>{formatCurrency(balanceReport.liabilities?.total_liabilities || 0)}</span>
                    </div>
                    {balanceReport.equity?.breakdown && Object.entries(balanceReport.equity.breakdown).map(([account, amount]) => (
                      <div key={account} className="flex justify-between p-2 bg-slate-50 rounded">
                        <span>{account}</span>
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </div>
                    ))}
                    <div className="flex justify-between p-3 bg-blue-50 rounded border-t-2 border-blue-500 font-semibold">
                      <span>Total Equity</span>
                      <span>{formatCurrency(balanceReport.equity?.total_equity || 0)}</span>
                    </div>
                    <div className={`flex justify-between p-3 rounded border-t-2 font-bold ${
                      balanceReport.balance?.is_balanced 
                        ? 'bg-green-50 border-green-500' 
                        : 'bg-red-50 border-red-500'
                    }`}>
                      <span>Total Liabilities & Equity</span>
                      <span>{formatCurrency(balanceReport.balance?.total_liabilities_and_equity || 0)}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div className={`mt-4 p-3 rounded ${
                balanceReport.balance?.is_balanced ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
              }`}>
                {balanceReport.balance?.is_balanced ? '✓ Balance Sheet is balanced' : '✗ Balance Sheet is not balanced'}
              </div>
            </div>
          )}

          {activeTab === 'tax' && taxReport && (
            <div className="bg-white rounded-xl shadow-lg p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold">Tax Report</h2>
                <div className="flex gap-2">
                  <button
                    onClick={() => handleExport('csv')}
                    className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2"
                  >
                    <Download className="w-4 h-4" />
                    Export CSV
                  </button>
                </div>
              </div>
              <div className="mb-6 p-4 bg-slate-50 rounded-lg">
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-slate-600">Total Tax Collected</p>
                    <p className="text-2xl font-bold text-emerald-600">{formatCurrency(taxReport.total_tax_collected || 0)}</p>
                  </div>
                  <div>
                    <p className="text-sm text-slate-600">Total Taxable Amount</p>
                    <p className="text-2xl font-bold">{formatCurrency(taxReport.total_taxable_amount || 0)}</p>
                  </div>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-slate-200">
                      <th className="text-left p-3">Invoice #</th>
                      <th className="text-left p-3">Customer</th>
                      <th className="text-right p-3">Taxable Amount</th>
                      <th className="text-right p-3">Tax Amount</th>
                      <th className="text-right p-3">Tax Rate</th>
                      <th className="text-left p-3">Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {taxReport.transactions?.map((tx, idx) => (
                      <tr key={idx} className="border-b border-slate-100 hover:bg-slate-50">
                        <td className="p-3">{tx.invoice_number}</td>
                        <td className="p-3">{tx.customer_name}</td>
                        <td className="p-3 text-right">{formatCurrency(tx.taxable_amount)}</td>
                        <td className="p-3 text-right font-semibold">{formatCurrency(tx.tax_amount)}</td>
                        <td className="p-3 text-right">{(tx.tax_rate * 100).toFixed(2)}%</td>
                        <td className="p-3">{formatDate(tx.transaction_date)}</td>
                      </tr>
                    )) || (
                      <tr>
                        <td colSpan={6} className="p-3 text-center text-slate-500">No transactions found</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default FinancialReportsPage;

