"use client";

import { useActionState, useEffect, useState } 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 { PlanLimitDialog } from "@/components/billing/plan-limit-dialog";
import {
  createSoftwareAction,
  updateSoftwareAction,
} from "@/lib/appwrite/software-actions";
import { initialSoftwareState } from "@/lib/appwrite/software-types";
import type { SoftwareRow } from "./types";

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

export function SoftwareFormSheet({ open, onOpenChange, software }: Props) {
  const isEdit = Boolean(software);
  const action = isEdit ? updateSoftwareAction : createSoftwareAction;
  const [state, formAction, isPending] = useActionState(action, initialSoftwareState);
  const [planLimitOpen, setPlanLimitOpen] = useState(false);

  useEffect(() => {
    if (state.ok) {
      toast.success(isEdit ? "Yazılım güncellendi." : "Yazılım 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]);

  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 ? "Yazılımı düzenle" : "Yeni yazılım"}</SheetTitle>
          <SheetDescription>
            Kataloğunuzdaki yazılım. Müşterilere ayrı ayrı ücretlerle atayabilirsiniz.
          </SheetDescription>
        </SheetHeader>

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

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <div className="grid gap-2">
              <Label htmlFor="name">Yazılım adı *</Label>
              <Input
                id="name"
                name="name"
                defaultValue={software?.name ?? ""}
                placeholder="Örn. Microsoft Office"
                required
              />
              {state.fieldErrors?.name && (
                <p className="text-destructive text-xs">{state.fieldErrors.name}</p>
              )}
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="version">Sürüm</Label>
                <Input
                  id="version"
                  name="version"
                  defaultValue={software?.version ?? ""}
                  placeholder="1.0.0"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="defaultFee">Varsayılan ücret (₺)</Label>
                <Input
                  id="defaultFee"
                  name="defaultFee"
                  type="number"
                  step="0.01"
                  min="0"
                  defaultValue={software?.defaultFee ?? ""}
                  placeholder="0.00"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="description">Açıklama</Label>
              <Textarea
                id="description"
                name="description"
                rows={3}
                defaultValue={software?.description ?? ""}
                placeholder="Yazılımın kapsamı, modülleri, 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>
      <PlanLimitDialog
        open={planLimitOpen}
        onOpenChange={setPlanLimitOpen}
        message={state.error}
      />
    </Sheet>
  );
}
