import {useState} from 'react';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {Button} from '@/components/ui/button';
import {useAppSelector} from '@/store';
import {AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer} from 'recharts';
import {format} from 'date-fns';
import AddAssetDialog from '@/components/dialogs/AddAssetDialog';
import AddLiabilityDialog from '@/components/dialogs/AddLiabilityDialog';

export default function NetWorthPage() {
  const [assetDialogOpen, setAssetDialogOpen] = useState(false);
  const [liabilityDialogOpen, setLiabilityDialogOpen] = useState(false);
  const {assets, liabilities, snapshots} = useAppSelector(state => state.netWorth);

  const chartData = snapshots.map(s => ({
    month: format(new Date(s.date), 'MMM'),
    netWorth: s.netWorth,
  }));

  const totalAssets = assets.reduce((sum, a) => sum + a.value, 0);
  const totalLiabilities = liabilities.reduce((sum, l) => sum + l.balance, 0);
  const netWorth = totalAssets - totalLiabilities;

  const fmt = (value: number) =>
    new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD', maximumFractionDigits: 0}).format(value);

  return (
    <div className="p-4">
      {/* Header + Summary inline */}
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-6">
          <h1 className="text-lg font-semibold">Net Worth</h1>
          <div className="flex gap-4 text-sm">
            <div><span className="text-muted-foreground">Assets</span> <span className="font-medium">{fmt(totalAssets)}</span></div>
            <div><span className="text-muted-foreground">Liabilities</span> <span className="font-medium">{fmt(totalLiabilities)}</span></div>
            <div><span className="text-muted-foreground">Net</span> <span className="font-semibold text-base">{fmt(netWorth)}</span></div>
          </div>
        </div>
        <Button size="sm">Record Snapshot</Button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {/* Chart - spans 2 cols */}
        <Card className="card-elevated col-span-2">
          <CardContent className="p-3">
            <div className="h-[200px]">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData}>
                  <defs>
                    <linearGradient id="netWorthGradient" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="oklch(0.7 0.08 260)" stopOpacity={0.3} />
                      <stop offset="100%" stopColor="oklch(0.7 0.08 260)" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <XAxis dataKey="month" stroke="oklch(0.5 0 0)" tick={{fill: 'oklch(0.5 0 0)', fontSize: 10}} axisLine={false} tickLine={false} />
                  <YAxis stroke="oklch(0.5 0 0)" tick={{fill: 'oklch(0.5 0 0)', fontSize: 10}} tickFormatter={v => `$${v / 1000}k`} axisLine={false} tickLine={false} width={45} />
                  <Tooltip
                    contentStyle={{background: 'oklch(0.28 0.01 260)', border: '1px solid oklch(1 0 0 / 0.1)', borderRadius: '6px', fontSize: 12}}
                    labelStyle={{color: 'oklch(0.9 0 0)'}}
                    formatter={(value: number) => [fmt(value), 'Net Worth']}
                  />
                  <Area type="monotone" dataKey="netWorth" stroke="oklch(0.7 0.08 260)" strokeWidth={2} fill="url(#netWorthGradient)" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Quick stats */}
        <div className="space-y-3">
          <Card className="card-elevated">
            <CardContent className="p-3">
              <p className="text-xs text-muted-foreground mb-1">Monthly Change</p>
              <p className="text-lg font-semibold text-green-400">+$7,500</p>
            </CardContent>
          </Card>
          <Card className="card-elevated">
            <CardContent className="p-3">
              <p className="text-xs text-muted-foreground mb-1">YTD Growth</p>
              <p className="text-lg font-semibold">+23.8%</p>
            </CardContent>
          </Card>
          <Card className="card-elevated">
            <CardContent className="p-3">
              <p className="text-xs text-muted-foreground mb-1">Accounts</p>
              <p className="text-lg font-semibold">{assets.length + liabilities.length}</p>
            </CardContent>
          </Card>
        </div>

        {/* Assets */}
        <Card className="card-elevated">
          <CardHeader className="flex flex-row items-center justify-between p-3 pb-2">
            <CardTitle className="text-sm font-medium">Assets</CardTitle>
            <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setAssetDialogOpen(true)}>+ Add</Button>
          </CardHeader>
          <CardContent className="p-3 pt-0">
            <div className="space-y-1.5 max-h-[180px] overflow-y-auto">
              {assets.map(asset => (
                <div key={asset.id} className="flex justify-between text-sm py-1 border-b border-border last:border-0">
                  <div>
                    <span>{asset.name}</span>
                    <span className="ml-1.5 text-xs text-muted-foreground capitalize">{asset.type}</span>
                  </div>
                  <span className="font-medium">{fmt(asset.value)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Liabilities */}
        <Card className="card-elevated">
          <CardHeader className="flex flex-row items-center justify-between p-3 pb-2">
            <CardTitle className="text-sm font-medium">Liabilities</CardTitle>
            <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setLiabilityDialogOpen(true)}>+ Add</Button>
          </CardHeader>
          <CardContent className="p-3 pt-0">
            <div className="space-y-1.5 max-h-[180px] overflow-y-auto">
              {liabilities.map(liability => (
                <div key={liability.id} className="flex justify-between text-sm py-1 border-b border-border last:border-0">
                  <div>
                    <span>{liability.name}</span>
                    <span className="ml-1.5 text-xs text-muted-foreground capitalize">{liability.type.replace('_', ' ')}</span>
                  </div>
                  <span className="font-medium">{fmt(liability.balance)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Asset Allocation */}
        <Card className="card-elevated">
          <CardHeader className="p-3 pb-2">
            <CardTitle className="text-sm font-medium">Allocation</CardTitle>
          </CardHeader>
          <CardContent className="p-3 pt-0">
            <div className="space-y-2">
              {['cash', 'investment', 'property', 'vehicle'].map(type => {
                const total = assets.filter(a => a.type === type).reduce((s, a) => s + a.value, 0);
                const pct = totalAssets > 0 ? (total / totalAssets) * 100 : 0;
                if (total === 0) return null;
                return (
                  <div key={type} className="flex items-center gap-2">
                    <div className="flex-1">
                      <div className="flex justify-between text-xs mb-0.5">
                        <span className="capitalize">{type}</span>
                        <span>{pct.toFixed(0)}%</span>
                      </div>
                      <div className="h-1 rounded-full bg-secondary overflow-hidden">
                        <div className="h-full bg-foreground/40" style={{width: `${pct}%`}} />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>

      <AddAssetDialog open={assetDialogOpen} onOpenChange={setAssetDialogOpen} />
      <AddLiabilityDialog open={liabilityDialogOpen} onOpenChange={setLiabilityDialogOpen} />
    </div>
  );
}
