import { useEffect, useState } from 'react'
import { Card, CardHeader } from '@/components/ui/Card'
import { Skeleton } from '@/components/ui/Skeleton'
import {
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableHeader,
  TableCell,
} from '@/components/ui/Table'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { formatCurrency, formatDate } from '@/lib/utils'
import { financeApi } from '@/lib/api'
import {
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts'
import {
  Wallet,
  TrendingUp,
  TrendingDown,
  Plus,
  Search,
  Filter,
  MoreHorizontal,
  ArrowUpRight,
  ArrowDownRight,
} from 'lucide-react'

interface BalanceAccount {
  account: string
  amount: number
}

interface BalanceData {
  assets: BalanceAccount[]
  liabilities: BalanceAccount[]
  equity: BalanceAccount[] | null
  total_assets: number
  total_liabilities: number
  total_equity: number
  period: string
}

interface IncomeData {
  revenue: BalanceAccount[]
  expenses: BalanceAccount[]
  total_revenue: number
  total_expenses: number
  net_income: number
  period: string
}

interface MOMSData {
  moms_in: number
  moms_ut: number
  moms_att_betala: number
  period: string
}

interface AccountItem {
  id: string
  name: string
  balance: number
  type: string
}

interface InvoiceItem {
  id: string
  customer: string
  amount: number
  status: string
  due_date: string
}

interface CashflowData {
  inflow: number
  outflow: number
  net: number
  period: string
}

const tabs = ['Balance', 'Income', 'MOMS', 'Accounts', 'Invoices', 'Cashflow']

const COLORS = ['#2563EB', '#16A34A', '#D97706', '#DC2626', '#9CA3AF']

export function FinancePage() {
  const [activeTab, setActiveTab] = useState('Balance')
  const [searchQuery, setSearchQuery] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const [balance, setBalance] = useState<BalanceData | null>(null)
  const [income, setIncome] = useState<IncomeData | null>(null)
  const [moms, setMoms] = useState<MOMSData | null>(null)
  const [accounts, setAccounts] = useState<AccountItem[]>([])
  const [invoices, setInvoices] = useState<InvoiceItem[]>([])
  const [cashflow, setCashflow] = useState<CashflowData | null>(null)

  useEffect(() => {
    async function fetchData() {
      setLoading(true)
      setError('')
      try {
        const [balanceRes, incomeRes, momsRes, accountsRes, invoicesRes, cashflowRes] = await Promise.all([
          financeApi.balance(),
          financeApi.income(),
          financeApi.moms(),
          financeApi.accounts(),
          financeApi.invoices(),
          financeApi.cashflow(),
        ])

        setBalance(balanceRes as BalanceData)
        setIncome(incomeRes as IncomeData)
        setMoms(momsRes as MOMSData)
        setAccounts((accountsRes as { accounts: AccountItem[] }).accounts || [])
        setInvoices((invoicesRes as { invoices: InvoiceItem[] }).invoices || [])
        setCashflow(cashflowRes as unknown as CashflowData)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load finance data')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  const filteredAccounts = accounts.filter(
    (a) =>
      a.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      a.id.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const filteredInvoices = invoices.filter(
    (i) =>
      i.customer.toLowerCase().includes(searchQuery.toLowerCase()) ||
      i.id.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const expenseBreakdown = income?.expenses.map((e, i) => ({
    name: e.account,
    value: e.amount,
    color: COLORS[i % COLORS.length],
  })) || []

  if (loading) {
    return (
      <div className="space-y-8">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
        </div>
        <Skeleton className="h-[400px]" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-danger">{error}</p>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold text-text-primary">Finance</h1>
          <p className="text-sm text-text-secondary mt-0.5">Financial reports and accounting</p>
        </div>
        <Button icon={<Plus size={16} />}>New Invoice</Button>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary-light flex items-center justify-center text-primary">
              <Wallet size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(balance?.total_assets || 0)}</p>
              <p className="text-xs text-text-secondary">Total Assets</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-success-light flex items-center justify-center text-success">
              <TrendingUp size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(income?.total_revenue || 0)}</p>
              <p className="text-xs text-text-secondary">YTD Revenue</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-warning-light flex items-center justify-center text-warning">
              <TrendingDown size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(income?.total_expenses || 0)}</p>
              <p className="text-xs text-text-secondary">YTD Expenses</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Tabs + Search */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div className="flex items-center gap-1 bg-bg rounded-xl p-1 overflow-x-auto max-w-full">
          {tabs.map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors whitespace-nowrap ${
                activeTab === tab
                  ? 'bg-surface text-text-primary shadow-sm'
                  : 'text-text-secondary hover:text-text-primary'
              }`}
            >
              {tab}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-2 w-full sm:w-auto">
          <div className="relative flex-1 sm:flex-initial">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
            <input
              type="text"
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full sm:w-64 h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm text-text-primary placeholder:text-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary/30"
            />
          </div>
          <Button variant="secondary" size="sm" icon={<Filter size={14} />}>
            Filter
          </Button>
        </div>
      </div>

      {/* Tab Content */}
      {activeTab === 'Balance' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            <Card>
              <div className="flex items-center justify-between mb-3">
                <span className="text-sm text-text-secondary">Assets</span>
                <ArrowUpRight size={14} className="text-success" />
              </div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(balance?.total_assets || 0)}</p>
            </Card>
            <Card>
              <div className="flex items-center justify-between mb-3">
                <span className="text-sm text-text-secondary">Liabilities</span>
                <ArrowDownRight size={14} className="text-danger" />
              </div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(balance?.total_liabilities || 0)}</p>
            </Card>
            <Card>
              <div className="flex items-center justify-between mb-3">
                <span className="text-sm text-text-secondary">Equity</span>
                <ArrowUpRight size={14} className="text-success" />
              </div>
              <p className="text-2xl font-semibold text-text-primary">{formatCurrency(balance?.total_equity || 0)}</p>
            </Card>
          </div>
          <Card>
            <CardHeader title="Balance Sheet" subtitle={`Period: ${balance?.period || ''}`} />
            <div className="space-y-6">
              <div>
                <h4 className="text-sm font-semibold text-text-primary mb-3">Assets</h4>
                <div className="space-y-2">
                  {balance?.assets.map((account, idx) => (
                    <div key={idx} className="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
                      <div>
                        <p className="text-sm text-text-primary">{account.account}</p>
                      </div>
                      <p className="text-sm font-medium text-text-primary">{formatCurrency(account.amount)}</p>
                    </div>
                  ))}
                  {(!balance?.assets || balance.assets.length === 0) && (
                    <p className="text-text-secondary text-sm">No asset accounts</p>
                  )}
                </div>
              </div>
              <div>
                <h4 className="text-sm font-semibold text-text-primary mb-3">Liabilities</h4>
                <div className="space-y-2">
                  {balance?.liabilities.map((account, idx) => (
                    <div key={idx} className="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
                      <div>
                        <p className="text-sm text-text-primary">{account.account}</p>
                      </div>
                      <p className="text-sm font-medium text-text-primary">{formatCurrency(account.amount)}</p>
                    </div>
                  ))}
                  {(!balance?.liabilities || balance.liabilities.length === 0) && (
                    <p className="text-text-secondary text-sm">No liability accounts</p>
                  )}
                </div>
              </div>
              <div>
                <h4 className="text-sm font-semibold text-text-primary mb-3">Equity</h4>
                <div className="space-y-2">
                  {balance?.equity?.map((account, idx) => (
                    <div key={idx} className="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
                      <div>
                        <p className="text-sm text-text-primary">{account.account}</p>
                      </div>
                      <p className="text-sm font-medium text-text-primary">{formatCurrency(account.amount)}</p>
                    </div>
                  ))}
                  {(!balance?.equity || balance.equity?.length === 0) && (
                    <p className="text-text-secondary text-sm">No equity accounts</p>
                  )}
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'Income' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
            <Card className="lg:col-span-2">
              <CardHeader title="Income Statement" subtitle={`Period: ${income?.period || ''}`} />
              <div className="space-y-4">
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-4 bg-bg rounded-xl">
                    <p className="text-xs text-text-secondary mb-1">Revenue</p>
                    <p className="text-lg font-semibold text-text-primary">{formatCurrency(income?.total_revenue || 0)}</p>
                  </div>
                  <div className="p-4 bg-bg rounded-xl">
                    <p className="text-xs text-text-secondary mb-1">Expenses</p>
                    <p className="text-lg font-semibold text-text-primary">{formatCurrency(income?.total_expenses || 0)}</p>
                  </div>
                  <div className="p-4 bg-bg rounded-xl">
                    <p className="text-xs text-text-secondary mb-1">Net Income</p>
                    <p className="text-lg font-semibold text-success">{formatCurrency(income?.net_income || 0)}</p>
                  </div>
                </div>
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-text-primary">Revenue Accounts</h4>
                  {income?.revenue.map((r, idx) => (
                    <div key={idx} className="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
                      <p className="text-sm text-text-primary">{r.account}</p>
                      <p className="text-sm font-medium text-text-primary">{formatCurrency(r.amount)}</p>
                    </div>
                  ))}
                </div>
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-text-primary">Expense Accounts</h4>
                  {income?.expenses.map((e, idx) => (
                    <div key={idx} className="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
                      <p className="text-sm text-text-primary">{e.account}</p>
                      <p className="text-sm font-medium text-text-primary">{formatCurrency(e.amount)}</p>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
            <Card>
              <CardHeader title="Expense Breakdown" subtitle="By category" />
              {expenseBreakdown.length > 0 ? (
                <>
                  <div className="h-[220px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={expenseBreakdown}
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={90}
                          paddingAngle={4}
                          dataKey="value"
                        >
                          {expenseBreakdown.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip
                          content={({ active, payload }) => {
                            if (!active || !payload?.length) return null
                            const data = payload[0].payload as { name: string; value: number }
                            return (
                              <div className="bg-surface rounded-xl dropdown-shadow border border-border/60 px-3 py-2">
                                <p className="text-sm font-medium text-text-primary">{data.name}</p>
                                <p className="text-xs text-text-secondary">{formatCurrency(data.value)}</p>
                              </div>
                            )
                          }}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                  <div className="space-y-2 mt-2">
                    {expenseBreakdown.map((item) => (
                      <div key={item.name} className="flex items-center justify-between text-sm">
                        <div className="flex items-center gap-2">
                          <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color }} />
                          <span className="text-text-secondary">{item.name}</span>
                        </div>
                        <span className="font-medium text-text-primary">{formatCurrency(item.value)}</span>
                      </div>
                    ))}
                  </div>
                </>
              ) : (
                <div className="h-[200px] flex items-center justify-center text-text-secondary">
                  No expense data
                </div>
              )}
            </Card>
          </div>
        </div>
      )}

      {activeTab === 'MOMS' && (
        <Card>
          <CardHeader title="MOMS Report" subtitle={`Period: ${moms?.period || ''}`} />
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-6">
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">MOMS In (Input VAT)</p>
              <p className="text-lg font-semibold text-text-primary">{formatCurrency(moms?.moms_in || 0)}</p>
            </div>
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">MOMS Ut (Output VAT)</p>
              <p className="text-lg font-semibold text-text-primary">{formatCurrency(moms?.moms_ut || 0)}</p>
            </div>
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">MOMS att betala</p>
              <p className="text-lg font-semibold text-success">{formatCurrency(moms?.moms_att_betala || 0)}</p>
            </div>
          </div>
        </Card>
      )}

      {activeTab === 'Accounts' && (
        <Card>
          <CardHeader title="Chart of Accounts" subtitle="General ledger accounts" />
          <Table>
            <TableHead>
              <TableRow>
                <TableHeader>Account</TableHeader>
                <TableHeader>Number</TableHeader>
                <TableHeader>Type</TableHeader>
                <TableHeader align="right">Balance</TableHeader>
                <TableHeader align="right"></TableHeader>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredAccounts.map((account) => (
                <TableRow key={account.id}>
                  <TableCell>
                    <span className="font-medium">{account.name}</span>
                  </TableCell>
                  <TableCell>
                    <code className="text-xs bg-bg px-2 py-0.5 rounded-md">{account.id}</code>
                  </TableCell>
                  <TableCell>
                    <Badge variant={account.type === 'asset' ? 'success' : account.type === 'equity' ? 'primary' : 'warning'}>
                      {account.type}
                    </Badge>
                  </TableCell>
                  <TableCell align="right">{formatCurrency(account.balance)}</TableCell>
                  <TableCell align="right">
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                      <MoreHorizontal size={16} />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
              {filteredAccounts.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-text-secondary py-8">
                    No accounts found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </Card>
      )}

      {activeTab === 'Invoices' && (
        <Card>
          <CardHeader title="Invoices" subtitle="All invoices" />
          <Table>
            <TableHead>
              <TableRow>
                <TableHeader>Number</TableHeader>
                <TableHeader>Customer</TableHeader>
                <TableHeader align="right">Amount</TableHeader>
                <TableHeader>Status</TableHeader>
                <TableHeader>Due Date</TableHeader>
                <TableHeader align="right"></TableHeader>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredInvoices.map((invoice) => (
                <TableRow key={invoice.id}>
                  <TableCell>
                    <span className="font-medium">{invoice.id}</span>
                  </TableCell>
                  <TableCell>{invoice.customer}</TableCell>
                  <TableCell align="right">{formatCurrency(invoice.amount)}</TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        invoice.status === 'paid'
                          ? 'success'
                          : invoice.status === 'overdue'
                          ? 'danger'
                          : invoice.status === 'sent' || invoice.status === 'pending'
                          ? 'primary'
                          : 'default'
                      }
                    >
                      {invoice.status}
                    </Badge>
                  </TableCell>
                  <TableCell>{formatDate(invoice.due_date)}</TableCell>
                  <TableCell align="right">
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                      <MoreHorizontal size={16} />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
              {filteredInvoices.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-text-secondary py-8">
                    No invoices found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </Card>
      )}

      {activeTab === 'Cashflow' && (
        <Card>
          <CardHeader title="Cash Flow" subtitle={`Period: ${cashflow?.period || ''}`} />
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-6">
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">Inflow</p>
              <p className="text-lg font-semibold text-success">{formatCurrency(cashflow?.inflow || 0)}</p>
            </div>
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">Outflow</p>
              <p className="text-lg font-semibold text-danger">{formatCurrency(cashflow?.outflow || 0)}</p>
            </div>
            <div className="p-4 bg-bg rounded-xl">
              <p className="text-xs text-text-secondary mb-1">Net</p>
              <p className="text-lg font-semibold text-text-primary">{formatCurrency(cashflow?.net || 0)}</p>
            </div>
          </div>
        </Card>
      )}
    </div>
  )
}
