"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 {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import {
  createBankAccountAction,
  updateBankAccountAction,
} from "@/lib/appwrite/bank-account-actions";
import { initialBankAccountState } from "@/lib/appwrite/bank-account-types";
import { ScopeToggle } from "@/components/finance/scope-toggle";

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

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  account?: BankAccountRow | null;
};

export function BankFormSheet({ open, onOpenChange, account }: Props) {
  const isEdit = Boolean(account);
  const action = isEdit ? updateBankAccountAction : createBankAccountAction;
  const [state, formAction, isPending] = useActionState(action, initialBankAccountState);

  useEffect(() => {
    if (state.ok) {
      toast.success(isEdit ? "Hesap güncellendi." : "Hesap 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 ? "Hesabı düzenle" : "Yeni banka hesabı"}</SheetTitle>
          <SheetDescription>
            Açılış bakiyesi sonradan değiştirilirse bütün hareketler aynı kalır, sadece toplam
            kayar.
          </SheetDescription>
        </SheetHeader>

        <form action={formAction} className="flex flex-1 flex-col">
          {isEdit && account && <input type="hidden" name="id" value={account.id} />}

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <ScopeToggle defaultValue={(account as { scope?: "company" | "personal" } | null)?.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={account?.bankName ?? ""}
                  placeholder="Örn. Garanti BBVA"
                  required
                />
                {state.fieldErrors?.bankName && (
                  <p className="text-destructive text-xs">{state.fieldErrors.bankName}</p>
                )}
              </div>
              <div className="grid gap-2">
                <Label htmlFor="accountName">Hesap adı *</Label>
                <Input
                  id="accountName"
                  name="accountName"
                  defaultValue={account?.accountName ?? ""}
                  placeholder="Örn. Şirket TL Vadesiz"
                  required
                />
                {state.fieldErrors?.accountName && (
                  <p className="text-destructive text-xs">{state.fieldErrors.accountName}</p>
                )}
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="iban">IBAN</Label>
              <Input
                id="iban"
                name="iban"
                defaultValue={account?.iban ?? ""}
                placeholder="TR.. .... .... .... .... .... .."
                style={{ fontFamily: "monospace", textTransform: "uppercase" }}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="openingBalance">Açılış bakiyesi (₺)</Label>
              <Input
                id="openingBalance"
                name="openingBalance"
                type="number"
                step="0.01"
                defaultValue={account?.openingBalance ?? 0}
                placeholder="0.00"
              />
              <p className="text-muted-foreground text-xs">
                Bu hesabı sisteme eklediğinizdeki bakiye. Sonraki hareketler bu rakamın üstüne eklenir.
              </p>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="notes">Notlar</Label>
              <Textarea
                id="notes"
                name="notes"
                rows={3}
                defaultValue={account?.notes ?? ""}
                placeholder="Şube, yetkili, müşteri no, 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>
  );
}
