"use client";

import { useActionState, useEffect } 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 {
  createCreditCardAction,
  updateCreditCardAction,
} from "@/lib/appwrite/credit-card-actions";
import { initialCreditCardState } from "@/lib/appwrite/credit-card-types";
import { ScopeToggle } from "@/components/finance/scope-toggle";

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

const NONE = "__none__";

export function CardFormSheet({
  open,
  onOpenChange,
  card,
  bankAccounts,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  card?: CreditCardRow | null;
  bankAccounts: BankAccountOption[];
}) {
  const isEdit = Boolean(card);
  const action = isEdit ? updateCreditCardAction : createCreditCardAction;
  const [state, formAction, isPending] = useActionState(action, initialCreditCardState);

  useEffect(() => {
    if (state.ok) {
      toast.success(isEdit ? "Kart güncellendi." : "Kart eklendi.");
      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>{isEdit ? "Kartı düzenle" : "Yeni kredi kartı"}</SheetTitle>
          <SheetDescription>
            Hesap kesim ve son ödeme günleri her ay otomatik kullanılır. Ekstreler kart başına manuel girilir.
          </SheetDescription>
        </SheetHeader>

        <form
          action={(fd) => {
            if (fd.get("bankAccountId") === NONE) fd.set("bankAccountId", "");
            formAction(fd);
          }}
          className="flex flex-1 flex-col"
        >
          {isEdit && card && <input type="hidden" name="id" value={card.id} />}

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <ScopeToggle defaultValue={card?.scope ?? "company"} />

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="bankName">Banka *</Label>
                <Input
                  id="bankName"
                  name="bankName"
                  defaultValue={card?.bankName ?? ""}
                  required
                  placeholder="Garanti BBVA"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="cardName">Kart adı *</Label>
                <Input
                  id="cardName"
                  name="cardName"
                  defaultValue={card?.cardName ?? ""}
                  required
                  placeholder="Bonus / Maximum / World"
                />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="last4">Son 4 hane</Label>
                <Input
                  id="last4"
                  name="last4"
                  defaultValue={card?.last4 ?? ""}
                  maxLength={4}
                  inputMode="numeric"
                  placeholder="1234"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="creditLimit">Kredi limiti (₺)</Label>
                <Input
                  id="creditLimit"
                  name="creditLimit"
                  type="number"
                  step="0.01"
                  min="0"
                  defaultValue={card?.creditLimit ?? 0}
                />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              <div className="grid gap-2">
                <Label htmlFor="statementDay">Hesap kesim günü</Label>
                <Input
                  id="statementDay"
                  name="statementDay"
                  type="number"
                  min="1"
                  max="28"
                  defaultValue={card?.statementDay ?? 1}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="dueDay">Son ödeme günü</Label>
                <Input
                  id="dueDay"
                  name="dueDay"
                  type="number"
                  min="1"
                  max="28"
                  defaultValue={card?.dueDay ?? 10}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="interestRate">Aylık faiz %</Label>
                <Input
                  id="interestRate"
                  name="interestRate"
                  type="number"
                  step="0.01"
                  min="0"
                  defaultValue={card?.interestRate ?? 4.25}
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="bankAccountId">Bağlı hesap</Label>
              <Select
                name="bankAccountId"
                defaultValue={card?.bankAccountId || NONE}
                disabled={bankAccounts.length === 0}
              >
                <SelectTrigger id="bankAccountId">
                  <SelectValue placeholder={bankAccounts.length === 0 ? "Önce hesap ekleyin" : "Yok"} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={NONE}>Yok</SelectItem>
                  {bankAccounts.map((b) => (
                    <SelectItem key={b.id} value={b.id}>
                      {b.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-muted-foreground text-xs">
                Ekstre ödemeleri seçilen hesaba expense olarak yazılır.
              </p>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="notes">Notlar</Label>
              <Textarea
                id="notes"
                name="notes"
                rows={3}
                defaultValue={card?.notes ?? ""}
                placeholder="Sadakat puanı, kampanya, vb."
              />
            </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" />
                    {isEdit ? "Güncelle" : "Kaydet"}
                  </>
                )}
              </Button>
            </div>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
