"use client";

import { useState } from "react";
import { Plus, TrendingUp, TrendingDown, Edit2, Trash2 } from "lucide-react";
import { useForm, type SubmitHandler, type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { assetSchema, type AssetInput } from "@/lib/validations/asset";
import {
  useNetWorth,
  useAssets,
  useCreateAsset,
  useUpdateAsset,
  useDeleteAsset,
} from "@/hooks/use-assets";
import { formatCents } from "@/lib/utils/format";
import type { Asset } from "@prisma/client";

const ASSET_TYPES = [
  { value: "REAL_ESTATE", label: "Real Estate" },
  { value: "VEHICLE", label: "Vehicle" },
  { value: "INVESTMENT", label: "Investment" },
  { value: "RETIREMENT", label: "Retirement" },
  { value: "SAVINGS_BOND", label: "Savings Bond" },
  { value: "CRYPTO", label: "Crypto" },
  { value: "BUSINESS_EQUITY", label: "Business Equity" },
  { value: "PERSONAL_PROPERTY", label: "Personal Property" },
  { value: "OTHER", label: "Other" },
];

function AssetDialog({
  open,
  onOpenChange,
  existing,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  existing?: Asset;
}) {
  const isEdit = !!existing;
  const create = useCreateAsset();
  const update = useUpdateAsset();

  const form = useForm<AssetInput>({
    resolver: zodResolver(assetSchema) as Resolver<AssetInput>,
    defaultValues: existing
      ? {
          name: existing.name,
          type: existing.type,
          currentValueCents: existing.currentValueCents,
          currency: existing.currency,
          purchasePriceCents: existing.purchasePriceCents ?? undefined,
          notes: existing.notes ?? undefined,
          includeInNetWorth: existing.includeInNetWorth,
        }
      : { type: "OTHER", currency: "USD", includeInNetWorth: true },
  });

  const onSubmit: SubmitHandler<AssetInput> = async (data) => {
    if (isEdit) {
      await update.mutateAsync({ id: existing.id, data });
    } else {
      await create.mutateAsync(data);
    }
    onOpenChange(false);
    form.reset();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-md">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit Asset" : "Add Asset"}</DialogTitle>
        </DialogHeader>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 mt-2">
          <div className="space-y-1">
            <Label className="text-slate-300">Asset Name</Label>
            <Input
              {...form.register("name")}
              placeholder="e.g. Home, Tesla, BTC"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
            {form.formState.errors.name && (
              <p className="text-red-400 text-xs">{form.formState.errors.name.message}</p>
            )}
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Type</Label>
              <select
                {...form.register("type")}
                className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              >
                {ASSET_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Currency</Label>
              <select
                {...form.register("currency")}
                className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              >
                {["USD", "EUR", "GBP", "LKR", "INR", "SGD", "AUD", "CAD"].map((c) => (
                  <option key={c} value={c}>{c}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Current Value ($)</Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("currentValueCents", {
                  setValueAs: (v) => Math.round(parseFloat(v) * 100),
                })}
                placeholder="50000.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Purchase Price ($)</Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("purchasePriceCents", {
                  setValueAs: (v) => v ? Math.round(parseFloat(v) * 100) : undefined,
                })}
                placeholder="Optional"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          <div className="space-y-1">
            <Label className="text-slate-300">Notes</Label>
            <Input
              {...form.register("notes")}
              placeholder="Optional notes"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
          </div>

          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              {...form.register("includeInNetWorth")}
              className="rounded border-slate-600 bg-slate-800 text-emerald-500"
            />
            <span className="text-sm text-slate-300">Include in net worth</span>
          </label>

          <div className="flex gap-3 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={create.isPending || update.isPending}
              className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {(create.isPending || update.isPending) ? "Saving…" : isEdit ? "Update" : "Add Asset"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function StatCard({
  label,
  value,
  positive,
}: {
  label: string;
  value: number;
  positive: boolean;
}) {
  const color = positive ? "text-emerald-400" : "text-red-400";
  const Icon = positive ? TrendingUp : TrendingDown;
  return (
    <Card className="bg-slate-800/50 border-slate-700/50">
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-xs text-slate-400">{label}</span>
          <Icon className={`h-4 w-4 ${color}`} />
        </div>
        <div className={`text-xl font-bold ${color}`}>{formatCents(value)}</div>
      </CardContent>
    </Card>
  );
}

export default function NetWorthPage() {
  const { data: nw, isLoading: nwLoading } = useNetWorth();
  const { data: assets, isLoading: assetsLoading } = useAssets();
  const deleteAsset = useDeleteAsset();
  const [assetDialog, setAssetDialog] = useState(false);
  const [editing, setEditing] = useState<Asset | undefined>();

  const netWorthColor = (nw?.netWorth ?? 0) >= 0 ? "text-emerald-400" : "text-red-400";

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-white">Net Worth</h1>
        <Button
          onClick={() => { setEditing(undefined); setAssetDialog(true); }}
          className="bg-emerald-600 hover:bg-emerald-500 text-white"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Asset
        </Button>
      </div>

      {/* Net Worth Headline */}
      <Card className="bg-gradient-to-br from-slate-800 to-slate-800/50 border-slate-700/50">
        <CardContent className="p-6 text-center">
          <p className="text-slate-400 text-sm mb-1">Total Net Worth</p>
          {nwLoading ? (
            <div className="h-10 w-48 bg-slate-700/50 rounded animate-pulse mx-auto" />
          ) : (
            <div className={`text-4xl font-bold ${netWorthColor}`}>
              {formatCents(nw?.netWorth ?? 0)}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Assets vs Liabilities */}
      <div className="grid grid-cols-2 gap-4">
        <StatCard label="Total Assets" value={nw?.totalAssets ?? 0} positive />
        <StatCard label="Total Liabilities" value={nw?.totalLiabilities ?? 0} positive={false} />
      </div>

      {/* Breakdown */}
      {nw && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* Assets side */}
          <div className="space-y-4">
            <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider">Assets</h2>

            {nw.breakdown.accounts.length > 0 && (
              <Card className="bg-slate-800/50 border-slate-700/50">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm text-slate-300">Bank Accounts</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  {nw.breakdown.accounts.map((a, i) => (
                    <div key={i} className="flex justify-between text-sm">
                      <span className="text-slate-400">{a.name}</span>
                      <span className="text-emerald-400">{formatCents(a.balanceCents)}</span>
                    </div>
                  ))}
                </CardContent>
              </Card>
            )}

            {nw.breakdown.assets.length > 0 && (
              <Card className="bg-slate-800/50 border-slate-700/50">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm text-slate-300">Other Assets</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  {nw.breakdown.assets.map((a, i) => (
                    <div key={i} className="flex justify-between text-sm">
                      <span className="text-slate-400">{a.name}</span>
                      <span className="text-emerald-400">{formatCents(a.currentValueCents)}</span>
                    </div>
                  ))}
                </CardContent>
              </Card>
            )}
          </div>

          {/* Liabilities side */}
          <div className="space-y-4">
            <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider">Liabilities</h2>

            {nw.breakdown.creditCards.length > 0 && (
              <Card className="bg-slate-800/50 border-slate-700/50">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm text-slate-300">Credit Cards</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  {nw.breakdown.creditCards.map((c, i) => (
                    <div key={i} className="flex justify-between text-sm">
                      <span className="text-slate-400">{c.name}</span>
                      <span className="text-red-400">{formatCents(c.balanceCents)}</span>
                    </div>
                  ))}
                </CardContent>
              </Card>
            )}

            {nw.breakdown.loans.length > 0 && (
              <Card className="bg-slate-800/50 border-slate-700/50">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm text-slate-300">Loans</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  {nw.breakdown.loans.map((l, i) => (
                    <div key={i} className="flex justify-between text-sm">
                      <span className="text-slate-400">{l.name}</span>
                      <span className="text-red-400">{formatCents(l.outstandingCents)}</span>
                    </div>
                  ))}
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      )}

      {/* Manage Assets */}
      <div>
        <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">Manage Assets</h2>
        {assetsLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="h-14 bg-slate-800/30 rounded-xl animate-pulse" />
            ))}
          </div>
        ) : !assets || assets.length === 0 ? (
          <p className="text-slate-500 text-sm text-center py-8">
            No assets added yet. Add one to track your real-world holdings.
          </p>
        ) : (
          <div className="space-y-2">
            {assets.map((asset) => (
              <Card key={asset.id} className="bg-slate-800/50 border-slate-700/50">
                <CardContent className="flex items-center justify-between py-3 px-4">
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-white text-sm">{asset.name}</span>
                      {!asset.includeInNetWorth && (
                        <span className="text-xs text-slate-600">(excluded)</span>
                      )}
                    </div>
                    <span className="text-xs text-slate-500">
                      {ASSET_TYPES.find((t) => t.value === asset.type)?.label}
                    </span>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="text-emerald-400 font-semibold text-sm">
                      {formatCents(asset.currentValueCents)}
                    </span>
                    <button
                      onClick={() => { setEditing(asset); setAssetDialog(true); }}
                      className="text-slate-500 hover:text-white transition-colors"
                    >
                      <Edit2 className="h-3.5 w-3.5" />
                    </button>
                    <button
                      onClick={() => deleteAsset.mutate(asset.id)}
                      className="text-slate-500 hover:text-red-400 transition-colors"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      <AssetDialog
        open={assetDialog}
        onOpenChange={(v) => { setAssetDialog(v); if (!v) setEditing(undefined); }}
        existing={editing}
      />
    </div>
  );
}
