"use client";

import { useActionState, useEffect, useMemo } from "react";
import { Loader2, Save } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import { createStatementAction } from "@/lib/appwrite/credit-card-actions";
import { initialCreditCardState } from "@/lib/appwrite/credit-card-types";

import type { CreditCardRow } from "./types";

function pad(n: number) {
  return String(n).padStart(2, "0");
}

function defaultDates(card?: CreditCardRow | null) {
  const now = new Date();
  const sd = card?.statementDay ?? 1;
  const dd = card?.dueDay ?? 10;
  const statement = new Date(now.getFullYear(), now.getMonth(), Math.min(sd, 28));
  const due = new Date(now.getFullYear(), now.getMonth(), Math.min(dd, 28));
  if (due.getTime() < statement.getTime()) due.setMonth(due.getMonth() + 1);
  const period = `${statement.getFullYear()}-${pad(statement.getMonth() + 1)}`;
  const ymd = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  return { period, statementDate: ymd(statement), dueDate: ymd(due) };
}

export function StatementFormSheet({
  open,
  onOpenChange,
  card,
  cards,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  card?: CreditCardRow | null;
  cards: CreditCardRow[];
}) {
  const [state, formAction, isPending] = useActionState(
    createStatementAction,
    initialCreditCardState,
  );
  const defaults = useMemo(() => defaultDates(card), [card]);

  useEffect(() => {
    if (state.ok) {
      toast.success("Ekstre kaydedildi.");
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state]);

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-xl">
        <SheetHeader className="border-b px-6 py-4">
          <SheetTitle>Yeni ekstre</SheetTitle>
          <SheetDescription>
            Banka ekstrenizdeki dönem, son ödeme tarihi, toplam borç ve asgari ödeme tutarını girin.
          </SheetDescription>
        </SheetHeader>

        <form action={formAction} className="flex flex-1 flex-col">
          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <div className="grid gap-2">
              <Label htmlFor="cardId">Kart *</Label>
              <Select name="cardId" defaultValue={card?.id ?? ""}>
                <SelectTrigger id="cardId">
                  <SelectValue placeholder="Kart seçin" />
                </SelectTrigger>
                <SelectContent>
                  {cards.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.bankName} — {c.cardName} {c.last4 ? `**${c.last4}` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {state.fieldErrors?.cardId && (
                <p className="text-destructive text-xs">{state.fieldErrors.cardId}</p>
              )}
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              <div className="grid gap-2">
                <Label htmlFor="period">Dönem (YYYY-AA) *</Label>
                <Input
                  id="period"
                  name="period"
                  defaultValue={defaults.period}
                  pattern="\d{4}-\d{2}"
                  required
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="statementDate">Hesap kesim *</Label>
                <Input
                  id="statementDate"
                  name="statementDate"
                  type="date"
                  defaultValue={defaults.statementDate}
                  required
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="dueDate">Son ödeme *</Label>
                <Input
                  id="dueDate"
                  name="dueDate"
                  type="date"
                  defaultValue={defaults.dueDate}
                  required
                />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="totalDebt">Toplam borç (₺) *</Label>
                <Input
                  id="totalDebt"
                  name="totalDebt"
                  type="number"
                  step="0.01"
                  min="0"
                  required
                  placeholder="0.00"
                />
                {state.fieldErrors?.totalDebt && (
                  <p className="text-destructive text-xs">{state.fieldErrors.totalDebt}</p>
                )}
              </div>
              <div className="grid gap-2">
                <Label htmlFor="minimumPayment">Asgari ödeme (₺)</Label>
                <Input
                  id="minimumPayment"
                  name="minimumPayment"
                  type="number"
                  step="0.01"
                  min="0"
                  placeholder="0.00"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="notes">Notlar</Label>
              <Textarea id="notes" name="notes" rows={3} placeholder="Önemli ekstre notları" />
            </div>
          </div>

          <SheetFooter className="border-t bg-muted/30 px-6 pt-4">
            <div className="flex w-full justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
                Vazgeç
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? (
                  <>
                    <Loader2 className="size-4 animate-spin" />
                    Kaydediliyor...
                  </>
                ) : (
                  <>
                    <Save className="size-4" />
                    Kaydet
                  </>
                )}
              </Button>
            </div>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
