"use client";

import { useState } from "react";
import { Plus, Handshake, ArrowUpRight, ArrowDownLeft, CheckCircle, Bell, Trash2, ChevronDown, ChevronUp } 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 } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { iouSchema, type IOUInput } from "@/lib/validations/iou";
import {
  useIOUs,
  useCreateIOU,
  useDeleteIOU,
  useMarkIOUSettled,
  useAddIOUPayment,
  useSendReminder,
  type IOUWithDetails,
} from "@/hooks/use-ious";
import { formatCents, formatDate } from "@/lib/utils/format";

const STATUS_COLORS: Record<string, string> = {
  PENDING: "bg-blue-500/20 text-blue-400 border-blue-500/30",
  PARTIALLY_PAID: "bg-amber-500/20 text-amber-400 border-amber-500/30",
  SETTLED: "bg-emerald-500/20 text-emerald-400 border-emerald-500/30",
  WRITTEN_OFF: "bg-slate-700 text-slate-400 border-slate-600",
};

function IOUDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {
  const create = useCreateIOU();

  const form = useForm<IOUInput>({
    resolver: zodResolver(iouSchema) as Resolver<IOUInput>,
    defaultValues: { direction: "THEY_OWE", currency: "USD" },
  });

  const onSubmit: SubmitHandler<IOUInput> = async (data) => {
    await create.mutateAsync({ ...data, dueDate: data.dueDate || undefined });
    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>Add IOU</DialogTitle>
        </DialogHeader>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 mt-2">
          <div className="space-y-1">
            <Label className="text-slate-300">Direction</Label>
            <div className="grid grid-cols-2 gap-2">
              {(["THEY_OWE", "I_OWE"] as const).map((d) => {
                const selected = form.watch("direction") === d;
                return (
                  <button
                    key={d}
                    type="button"
                    onClick={() => form.setValue("direction", d)}
                    className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors ${
                      selected
                        ? "border-emerald-500 bg-emerald-500/10 text-emerald-400"
                        : "border-slate-600 bg-slate-800 text-slate-400 hover:border-slate-500"
                    }`}
                  >
                    {d === "THEY_OWE" ? (
                      <ArrowDownLeft className="h-4 w-4" />
                    ) : (
                      <ArrowUpRight className="h-4 w-4" />
                    )}
                    {d === "THEY_OWE" ? "They Owe Me" : "I Owe Them"}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="space-y-1">
            <Label className="text-slate-300">Person Name</Label>
            <Input
              {...form.register("counterpartyName")}
              placeholder="John Doe"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
            {form.formState.errors.counterpartyName && (
              <p className="text-red-400 text-xs">{form.formState.errors.counterpartyName.message}</p>
            )}
          </div>

          <div className="space-y-1">
            <Label className="text-slate-300">Email (for reminders)</Label>
            <Input
              {...form.register("counterpartyEmail")}
              type="email"
              placeholder="john@example.com (optional)"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
          </div>

          <div className="space-y-1">
            <Label className="text-slate-300">Description</Label>
            <Input
              {...form.register("description")}
              placeholder="Dinner split, travel loan, etc."
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
            {form.formState.errors.description && (
              <p className="text-red-400 text-xs">{form.formState.errors.description.message}</p>
            )}
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Amount ($)</Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("principalCents", {
                  setValueAs: (v) => Math.round(parseFloat(v) * 100),
                })}
                placeholder="100.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              {form.formState.errors.principalCents && (
                <p className="text-red-400 text-xs">{form.formState.errors.principalCents.message}</p>
              )}
            </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="space-y-1">
            <Label className="text-slate-300">Due Date (optional)</Label>
            <Input
              type="date"
              {...form.register("dueDate")}
              className="bg-slate-800 border-slate-600 text-white"
            />
          </div>

          <div className="space-y-1">
            <Label className="text-slate-300">Notes (optional)</Label>
            <Textarea
              {...form.register("notes")}
              placeholder="Any additional context…"
              rows={2}
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500 resize-none"
            />
          </div>

          <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}
              className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {create.isPending ? "Saving…" : "Add IOU"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function PaymentDialog({
  iou,
  open,
  onOpenChange,
}: {
  iou: IOUWithDetails;
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const addPayment = useAddIOUPayment();
  const [amount, setAmount] = useState("");
  const [notes, setNotes] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const cents = Math.round(parseFloat(amount) * 100);
    if (!cents || cents <= 0) return;
    await addPayment.mutateAsync({ id: iou.id, amountCents: cents, notes: notes || undefined });
    onOpenChange(false);
    setAmount("");
    setNotes("");
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-sm">
        <DialogHeader>
          <DialogTitle>Record Payment</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 mt-2">
          <p className="text-sm text-slate-400">
            Remaining: <span className="text-white font-medium">{formatCents(iou.remainingCents)}</span>
          </p>
          <div className="space-y-1">
            <Label className="text-slate-300">Amount ($)</Label>
            <Input
              type="number"
              step="0.01"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              placeholder={(iou.remainingCents / 100).toFixed(2)}
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
          </div>
          <div className="space-y-1">
            <Label className="text-slate-300">Notes (optional)</Label>
            <Input
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Cash / bank transfer / etc."
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
          </div>
          <div className="flex gap-3">
            <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={addPayment.isPending || !amount}
              className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {addPayment.isPending ? "Saving…" : "Record"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function ReminderDialog({
  iou,
  open,
  onOpenChange,
}: {
  iou: IOUWithDetails;
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const sendReminder = useSendReminder();
  const [email, setEmail] = useState(iou.counterpartyEmail ?? "");
  const [msg, setMsg] = useState<string | null>(null);

  const handleSend = async () => {
    if (!email) return;
    await sendReminder.mutateAsync({
      id: iou.id,
      recipientEmail: email,
      scheduledAt: new Date().toISOString(),
      reminderType: "CUSTOM",
    });
    setMsg("Reminder sent!");
    setTimeout(() => { setMsg(null); onOpenChange(false); }, 1500);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-sm">
        <DialogHeader>
          <DialogTitle>Send Reminder</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 mt-2">
          <p className="text-sm text-slate-400">
            Send a payment reminder email for <span className="text-white">{iou.description}</span>
          </p>
          <div className="space-y-1">
            <Label className="text-slate-300">Send To</Label>
            <Input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="email@example.com"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
          </div>
          {msg && <p className="text-emerald-400 text-sm">{msg}</p>}
          <div className="flex gap-3">
            <Button
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800"
            >
              Cancel
            </Button>
            <Button
              disabled={sendReminder.isPending || !email}
              onClick={handleSend}
              className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {sendReminder.isPending ? "Sending…" : "Send"}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

function IOUCard({ iou }: { iou: IOUWithDetails }) {
  const deleteIOU = useDeleteIOU();
  const markSettled = useMarkIOUSettled();
  const [paymentOpen, setPaymentOpen] = useState(false);
  const [reminderOpen, setReminderOpen] = useState(false);
  const [showHistory, setShowHistory] = useState(false);

  const isSettled = iou.status === "SETTLED" || iou.status === "WRITTEN_OFF";
  const progress = iou.principalCents > 0
    ? ((iou.principalCents - iou.remainingCents) / iou.principalCents) * 100
    : 0;

  return (
    <>
      <Card className="bg-slate-800/50 border-slate-700/50">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-2">
              <div className={`mt-0.5 p-1 rounded ${iou.direction === "THEY_OWE" ? "bg-emerald-500/20" : "bg-red-500/20"}`}>
                {iou.direction === "THEY_OWE"
                  ? <ArrowDownLeft className="h-3.5 w-3.5 text-emerald-400" />
                  : <ArrowUpRight className="h-3.5 w-3.5 text-red-400" />
                }
              </div>
              <div>
                <div className="font-medium text-white">{iou.counterpartyName}</div>
                <div className="text-xs text-slate-400">{iou.description}</div>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Badge className={`text-xs ${STATUS_COLORS[iou.status]}`}>
                {iou.status.replace("_", " ")}
              </Badge>
              <button
                onClick={() => deleteIOU.mutate(iou.id)}
                className="text-slate-600 hover:text-red-400 transition-colors"
              >
                <Trash2 className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>

          <div className="flex items-end justify-between">
            <div>
              <div className="text-xl font-bold text-white">{formatCents(iou.remainingCents)}</div>
              {iou.remainingCents !== iou.principalCents && (
                <div className="text-xs text-slate-500">of {formatCents(iou.principalCents)}</div>
              )}
            </div>
            {iou.dueDate && (
              <div className="text-xs text-slate-500">Due {formatDate(iou.dueDate)}</div>
            )}
          </div>

          {progress > 0 && (
            <div className="h-1.5 w-full bg-slate-700 rounded-full overflow-hidden">
              <div
                className="h-full bg-emerald-500 rounded-full transition-all"
                style={{ width: `${progress}%` }}
              />
            </div>
          )}

          {!isSettled && (
            <div className="flex gap-2 pt-1">
              <Button
                size="sm"
                onClick={() => setPaymentOpen(true)}
                className="flex-1 h-7 text-xs bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-400 border border-emerald-500/30"
                variant="outline"
              >
                <CheckCircle className="h-3.5 w-3.5 mr-1" />
                Payment
              </Button>
              {iou.counterpartyEmail && (
                <Button
                  size="sm"
                  onClick={() => setReminderOpen(true)}
                  className="h-7 text-xs bg-slate-700/50 hover:bg-slate-700 text-slate-400 border-slate-600"
                  variant="outline"
                >
                  <Bell className="h-3.5 w-3.5" />
                </Button>
              )}
              <Button
                size="sm"
                onClick={() => markSettled.mutate(iou.id)}
                disabled={markSettled.isPending}
                className="h-7 text-xs bg-slate-700/50 hover:bg-slate-700 text-slate-400 border-slate-600"
                variant="outline"
              >
                Settle
              </Button>
            </div>
          )}

          {iou.partialPayments.length > 0 && (
            <button
              onClick={() => setShowHistory((v) => !v)}
              className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-300 transition-colors"
            >
              {showHistory ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
              {iou.partialPayments.length} payment{iou.partialPayments.length > 1 ? "s" : ""}
            </button>
          )}

          {showHistory && (
            <div className="space-y-1">
              {iou.partialPayments.map((p) => (
                <div key={p.id} className="flex justify-between text-xs text-slate-400 py-1 border-t border-slate-700/30">
                  <span>{formatDate(p.paidAt)}{p.notes ? ` · ${p.notes}` : ""}</span>
                  <span className="text-emerald-400">+{formatCents(p.amountCents)}</span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <PaymentDialog iou={iou} open={paymentOpen} onOpenChange={setPaymentOpen} />
      <ReminderDialog iou={iou} open={reminderOpen} onOpenChange={setReminderOpen} />
    </>
  );
}

export default function IOUsPage() {
  const [addOpen, setAddOpen] = useState(false);
  const [tab, setTab] = useState("active");

  const statusFilter = tab === "active" ? undefined : "SETTLED";
  const { data: ious, isLoading } = useIOUs(statusFilter);

  const iOwe = ious?.filter((i) => i.direction === "I_OWE" && i.status !== "SETTLED") ?? [];
  const theyOwe = ious?.filter((i) => i.direction === "THEY_OWE" && i.status !== "SETTLED") ?? [];
  const settled = ious?.filter((i) => i.status === "SETTLED" || i.status === "WRITTEN_OFF") ?? [];

  const totalTheyOwe = theyOwe.reduce((s, i) => s + i.remainingCents, 0);
  const totalIOwe = iOwe.reduce((s, i) => s + i.remainingCents, 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">IOUs</h1>
          {(totalTheyOwe > 0 || totalIOwe > 0) && (
            <p className="text-slate-400 text-sm mt-1">
              {totalTheyOwe > 0 && <span className="text-emerald-400">+{formatCents(totalTheyOwe)} owed to you</span>}
              {totalTheyOwe > 0 && totalIOwe > 0 && " · "}
              {totalIOwe > 0 && <span className="text-red-400">−{formatCents(totalIOwe)} you owe</span>}
            </p>
          )}
        </div>
        <Button
          onClick={() => setAddOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-500 text-white"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add IOU
        </Button>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList className="bg-slate-800 border border-slate-700">
          <TabsTrigger value="active" className="data-[state=active]:bg-slate-700 data-[state=active]:text-white text-slate-400">
            Active
          </TabsTrigger>
          <TabsTrigger value="settled" className="data-[state=active]:bg-slate-700 data-[state=active]:text-white text-slate-400">
            Settled
          </TabsTrigger>
        </TabsList>

        <TabsContent value="active" className="mt-4">
          {isLoading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="h-40 bg-slate-800/30 rounded-xl animate-pulse" />
              ))}
            </div>
          ) : iOwe.length === 0 && theyOwe.length === 0 ? (
            <Card className="bg-slate-800/30 border-slate-700/50 border-dashed">
              <CardContent className="flex flex-col items-center justify-center py-16 text-center">
                <Handshake className="h-10 w-10 text-slate-600 mb-3" />
                <p className="text-slate-400 font-medium">No active IOUs</p>
                <p className="text-slate-500 text-sm mt-1">
                  Track money you lend or borrow from friends
                </p>
                <Button onClick={() => setAddOpen(true)} className="mt-4 bg-emerald-600 hover:bg-emerald-500 text-white">
                  <Plus className="h-4 w-4 mr-2" />
                  Add IOU
                </Button>
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-6">
              {theyOwe.length > 0 && (
                <div>
                  <h2 className="text-sm font-medium text-emerald-400 mb-3 flex items-center gap-1.5">
                    <ArrowDownLeft className="h-4 w-4" />
                    They Owe Me ({theyOwe.length})
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {theyOwe.map((iou) => <IOUCard key={iou.id} iou={iou} />)}
                  </div>
                </div>
              )}
              {iOwe.length > 0 && (
                <div>
                  <h2 className="text-sm font-medium text-red-400 mb-3 flex items-center gap-1.5">
                    <ArrowUpRight className="h-4 w-4" />
                    I Owe ({iOwe.length})
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {iOwe.map((iou) => <IOUCard key={iou.id} iou={iou} />)}
                  </div>
                </div>
              )}
            </div>
          )}
        </TabsContent>

        <TabsContent value="settled" className="mt-4">
          {settled.length === 0 ? (
            <p className="text-slate-500 text-sm text-center py-12">No settled IOUs yet</p>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {settled.map((iou) => <IOUCard key={iou.id} iou={iou} />)}
            </div>
          )}
        </TabsContent>
      </Tabs>

      <IOUDialog open={addOpen} onOpenChange={setAddOpen} />
    </div>
  );
}
