import React, { useState, useEffect } from 'react';
import { BookOpen, Plus, Calendar, FileText, Lock } from 'lucide-react';
import { toast } from 'react-toastify';
import glService, { Account, FiscalPeriod, JournalEntry } from '../../features/payments/services/glService';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { formatDate } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';

const GLManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [activeTab, setActiveTab] = useState<'accounts' | 'periods' | 'entries'>('accounts');
  const [loading, setLoading] = useState(true);
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [periods, setPeriods] = useState<FiscalPeriod[]>([]);
  const [entries, setEntries] = useState<JournalEntry[]>([]);
  const [selectedPeriod, setSelectedPeriod] = useState<number | null>(null);

  useEffect(() => {
    fetchData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, selectedPeriod]);

  const fetchData = async () => {
    try {
      setLoading(true);
      if (activeTab === 'accounts') {
        const response = await glService.getAccounts();
        setAccounts(response.data.accounts || []);
      } else if (activeTab === 'periods') {
        const response = await glService.getFiscalPeriods();
        setPeriods(response.data.fiscal_periods || []);
      } else if (activeTab === 'entries') {
        const params: { limit: number; fiscal_period_id?: number } = { limit: 50 };
        if (selectedPeriod) params.fiscal_period_id = selectedPeriod;
        const response = await glService.getJournalEntries(params);
        setEntries(response.data.journal_entries || []);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const handleClosePeriod = async (periodId: number) => {
    if (!confirm('Are you sure you want to close this fiscal period? This action may require approval.')) {
      return;
    }
    try {
      await glService.closeFiscalPeriod(periodId, false);
      toast.success('Fiscal period closed successfully');
      fetchData();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to close period');
    }
  };

  if (loading && accounts.length === 0 && periods.length === 0 && entries.length === 0) {
    return <Loading fullScreen text="Loading General Ledger..." />;
  }

  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">
            General Ledger
          </h1>
        </div>
        <p className="text-slate-600 text-sm sm:text-base md:text-lg font-light">
          Manage chart of accounts, fiscal periods, and journal entries
        </p>
      </div>

      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-6 border-b border-slate-200">
        <button
          onClick={() => setActiveTab('accounts')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'accounts'
              ? 'bg-emerald-500 text-white border-b-2 border-emerald-600'
              : 'text-slate-600 hover:text-emerald-600'
          }`}
        >
          <BookOpen className="inline w-4 h-4 mr-2" />
          Chart of Accounts
        </button>
        <button
          onClick={() => setActiveTab('periods')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'periods'
              ? 'bg-emerald-500 text-white border-b-2 border-emerald-600'
              : 'text-slate-600 hover:text-emerald-600'
          }`}
        >
          <Calendar className="inline w-4 h-4 mr-2" />
          Fiscal Periods
        </button>
        <button
          onClick={() => setActiveTab('entries')}
          className={`px-4 py-2 font-semibold rounded-t-lg transition-colors ${
            activeTab === 'entries'
              ? '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" />
          Journal Entries
        </button>
      </div>

      {/* Content */}
      {activeTab === 'accounts' && (
        <div className="bg-white rounded-xl shadow-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold">Chart of Accounts</h2>
            <button className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2">
              <Plus className="w-4 h-4" />
              Add Account
            </button>
          </div>
          {accounts.length === 0 ? (
            <EmptyState title="No Accounts" description="Chart of accounts will appear here" />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-200">
                    <th className="text-left p-3">Account #</th>
                    <th className="text-left p-3">Account Name</th>
                    <th className="text-left p-3">Type</th>
                    <th className="text-left p-3">Category</th>
                    <th className="text-left p-3">Normal Balance</th>
                    <th className="text-left p-3">Status</th>
                  </tr>
                </thead>
                <tbody>
                  {accounts.map((account) => (
                    <tr key={account.id} className="border-b border-slate-100 hover:bg-slate-50">
                      <td className="p-3 font-mono">{account.account_number}</td>
                      <td className="p-3 font-semibold">{account.account_name}</td>
                      <td className="p-3">{account.account_type}</td>
                      <td className="p-3">{account.account_category}</td>
                      <td className="p-3">{account.normal_balance}</td>
                      <td className="p-3">
                        <span className={`px-2 py-1 rounded-full text-xs ${
                          account.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                        }`}>
                          {account.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {activeTab === 'periods' && (
        <div className="bg-white rounded-xl shadow-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold">Fiscal Periods</h2>
            <button className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2">
              <Plus className="w-4 h-4" />
              Create Period
            </button>
          </div>
          {periods.length === 0 ? (
            <EmptyState title="No Fiscal Periods" description="Fiscal periods will appear here" />
          ) : (
            <div className="space-y-4">
              {periods.map((period) => (
                <div key={period.id} className="border border-slate-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex justify-between items-start">
                    <div>
                      <h3 className="font-bold text-lg">{period.name}</h3>
                      <p className="text-sm text-slate-600">
                        {formatDate(period.start_date)} - {formatDate(period.end_date)}
                      </p>
                      <div className="flex gap-2 mt-2">
                        <span className={`px-2 py-1 rounded-full text-xs ${
                          period.status === 'Open' ? 'bg-green-100 text-green-800' :
                          period.status === 'Closed' ? 'bg-blue-100 text-blue-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {period.status}
                        </span>
                        {period.is_current && (
                          <span className="px-2 py-1 rounded-full text-xs bg-emerald-100 text-emerald-800">
                            Current
                          </span>
                        )}
                      </div>
                    </div>
                    {period.status === 'Open' && (
                      <button
                        onClick={() => handleClosePeriod(period.id)}
                        className="px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 flex items-center gap-2"
                      >
                        <Lock className="w-4 h-4" />
                        Close Period
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === 'entries' && (
        <div className="bg-white rounded-xl shadow-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold">Journal Entries</h2>
            <div className="flex gap-2">
              <select
                value={selectedPeriod || ''}
                onChange={(e) => setSelectedPeriod(e.target.value ? parseInt(e.target.value) : null)}
                className="px-4 py-2 border border-slate-300 rounded-lg"
              >
                <option value="">All Periods</option>
                {periods.map((p) => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </select>
              <button className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2">
                <Plus className="w-4 h-4" />
                New Entry
              </button>
            </div>
          </div>
          {entries.length === 0 ? (
            <EmptyState title="No Journal Entries" description="Journal entries will appear here" />
          ) : (
            <div className="space-y-4">
              {entries.map((entry) => (
                <div key={entry.id} className="border border-slate-200 rounded-lg p-4">
                  <div className="flex justify-between items-start mb-2">
                    <div>
                      <h3 className="font-bold">{entry.description}</h3>
                      <p className="text-sm text-slate-600">{formatDate(entry.entry_date)}</p>
                      <p className="text-xs text-slate-500">{entry.entry_type}</p>
                    </div>
                  </div>
                  <div className="mt-3 overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-slate-200">
                          <th className="text-left p-2">Account</th>
                          <th className="text-right p-2">Debit</th>
                          <th className="text-right p-2">Credit</th>
                        </tr>
                      </thead>
                      <tbody>
                        {entry.journal_lines?.map((line) => (
                          <tr key={line.id} className="border-b border-slate-100">
                            <td className="p-2">{line.account?.account_name}</td>
                            <td className="p-2 text-right">{line.debit > 0 ? formatCurrency(line.debit) : '-'}</td>
                            <td className="p-2 text-right">{line.credit > 0 ? formatCurrency(line.credit) : '-'}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default GLManagementPage;

