"use client";

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

import { PlanLimitDialog } from "@/components/billing/plan-limit-dialog";

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 {
  createFinanceEntryAction,
  updateFinanceEntryAction,
} from "@/lib/appwrite/finance-actions";
import { initialFinanceState } from "@/lib/appwrite/finance-types";
import { ScopeToggle } from "@/components/finance/scope-toggle";

import type { BankAccountOption, Customer, FinanceRow, FinanceType } from "./types";

const NONE = "__none__";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  entry?: FinanceRow | null;
  defaultType?: FinanceType;
  customers: Customer[];
  bankAccounts: BankAccountOption[];
  onRequestDelete?: (entry: FinanceRow) => void;
};

function isoToDate(iso: string): string {
  if (!iso) return "";
  return iso.slice(0, 10);
}

export function FinanceFormSheet({
  open,
  onOpenChange,
  entry,
  defaultType = "income",
  customers,
  bankAccounts,
  onRequestDelete,
}: Props) {
  const isEdit = Boolean(entry);
  const action = isEdit ? updateFinanceEntryAction : createFinanceEntryAction;
  const [state, formAction, isPending] = useActionState(action, initialFinanceState);
  const [planLimitOpen, setPlanLimitOpen] = useState(false);

  useEffect(() => {
    if (state.ok) {
      toast.success(isEdit ? "Kayıt güncellendi." : "Kayıt eklendi.");
      onOpenChange(false);
    } else if (state.code === "PLAN_LIMIT_EXCEEDED") {
      setPlanLimitOpen(true);
    } else if (state.error) {
      toast.error(state.error);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state]);

  const today = new Date().toISOString().slice(0, 10);

  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 ? "Kaydı düzenle" : "Yeni kayıt"}</SheetTitle>
          <SheetDescription>
            Gelir, gider, borç veya alacak girişi. Borç = ödeyeceğiniz, Alacak = tahsil edeceğiniz.
          </SheetDescription>
        </SheetHeader>

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

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <ScopeToggle
              defaultValue={(entry as { scope?: "company" | "personal" } | null | undefined)?.scope ?? "company"}
            />

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="type">Tür *</Label>
                <Select name="type" defaultValue={entry?.type ?? defaultType}>
                  <SelectTrigger id="type">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="income">Gelir</SelectItem>
                    <SelectItem value="expense">Gider</SelectItem>
                    <SelectItem value="receivable">Alacak</SelectItem>
                    <SelectItem value="debt">Borç</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="amount">Tutar (₺) *</Label>
                <Input
                  id="amount"
                  name="amount"
                  type="number"
                  step="0.01"
                  min="0.01"
                  defaultValue={entry?.amount ?? ""}
                  placeholder="0.00"
                  required
                />
                {state.fieldErrors?.amount && (
                  <p className="text-destructive text-xs">{state.fieldErrors.amount}</p>
                )}
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="date">Tarih *</Label>
                <Input
                  id="date"
                  name="date"
                  type="date"
                  defaultValue={isoToDate(entry?.date ?? today)}
                  required
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="paymentMethod">Ödeme yöntemi</Label>
                <Select
                  name="paymentMethod"
                  defaultValue={entry?.paymentMethod || NONE}
                >
                  <SelectTrigger id="paymentMethod">
                    <SelectValue placeholder="Belirtilmemiş" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE}>Belirtilmemiş</SelectItem>
                    <SelectItem value="cash">Nakit</SelectItem>
                    <SelectItem value="transfer">Havale / EFT</SelectItem>
                    <SelectItem value="card">Kart</SelectItem>
                    <SelectItem value="check">Çek</SelectItem>
                    <SelectItem value="other">Diğer</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
                <Select name="customerId" defaultValue={entry?.customerId || NONE}>
                  <SelectTrigger id="customerId">
                    <SelectValue placeholder="Yok" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE}>Yok</SelectItem>
                    {customers.map((c) => (
                      <SelectItem key={c.id} value={c.id}>
                        {c.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="bankAccountId">Banka hesabı</Label>
                <Select
                  name="bankAccountId"
                  defaultValue={entry?.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>
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="description">Açıklama</Label>
              <Textarea
                id="description"
                name="description"
                rows={3}
                defaultValue={entry?.description ?? ""}
                placeholder="Hangi kalem, hangi fatura, vb."
              />
            </div>
          </div>

          <SheetFooter className="border-t bg-muted/30 px-6 pt-4">
            <div className="flex w-full items-center justify-between gap-2">
              <div>
                {isEdit && entry && onRequestDelete && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="text-destructive hover:text-destructive"
                    onClick={() => onRequestDelete(entry)}
                    disabled={isPending}
                  >
                    <Trash2 className="size-3.5" />
                    Sil
                  </Button>
                )}
              </div>
              <div className="flex 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>
            </div>
          </SheetFooter>
        </form>
      </SheetContent>
      <PlanLimitDialog
        open={planLimitOpen}
        onOpenChange={setPlanLimitOpen}
        message={state.error}
      />
    </Sheet>
  );
}
