"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 { createTaskAction, updateTaskAction } from "@/lib/appwrite/task-actions";
import { initialTaskState } from "@/lib/appwrite/task-types";
import type { Customer, TaskRow, TaskStatus, TeamMember } from "./types";

const NONE = "__none__";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  task?: TaskRow | null;
  defaultStatus?: TaskStatus;
  customers: Customer[];
  teamMembers: TeamMember[];
};

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

export function TaskFormSheet({
  open,
  onOpenChange,
  task,
  defaultStatus = "todo",
  customers,
  teamMembers,
}: Props) {
  const isEdit = Boolean(task);
  const action = isEdit ? updateTaskAction : createTaskAction;
  const [state, formAction, isPending] = useActionState(action, initialTaskState);

  useEffect(() => {
    if (state.ok) {
      toast.success(isEdit ? "Görev güncellendi." : "Görev 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 ? "Görevi düzenle" : "Yeni görev"}</SheetTitle>
          <SheetDescription>
            Görev bilgilerini doldurun. Sonra Kanban'da sürükleyerek durumu değiştirebilirsiniz.
          </SheetDescription>
        </SheetHeader>

        <form
          action={(fd) => {
            // Strip "__none__" sentinel before submit
            ["assigneeId", "customerId"].forEach((k) => {
              if (fd.get(k) === NONE) fd.set(k, "");
            });
            formAction(fd);
          }}
          className="flex flex-1 flex-col"
        >
          {isEdit && task && <input type="hidden" name="id" value={task.id} />}

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            <div className="grid gap-2">
              <Label htmlFor="title">Başlık *</Label>
              <Input
                id="title"
                name="title"
                defaultValue={task?.title ?? ""}
                placeholder="Örn. Müşteriyi ara"
                required
              />
              {state.fieldErrors?.title && (
                <p className="text-destructive text-xs">{state.fieldErrors.title}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="description">Açıklama</Label>
              <Textarea
                id="description"
                name="description"
                rows={4}
                defaultValue={task?.description ?? ""}
                placeholder="Detaylar, kabul kriterleri, vb."
              />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="status">Durum</Label>
                <Select name="status" defaultValue={task?.status ?? defaultStatus}>
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="backlog">Beklemede</SelectItem>
                    <SelectItem value="todo">Yapılacak</SelectItem>
                    <SelectItem value="in_progress">Sürüyor</SelectItem>
                    <SelectItem value="done">Bitti</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="priority">Öncelik</Label>
                <Select name="priority" defaultValue={task?.priority ?? "medium"}>
                  <SelectTrigger id="priority">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="low">Düşük</SelectItem>
                    <SelectItem value="medium">Orta</SelectItem>
                    <SelectItem value="high">Yüksek</SelectItem>
                    <SelectItem value="urgent">Acil</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="dueDate">Son tarih</Label>
                <Input
                  id="dueDate"
                  name="dueDate"
                  type="date"
                  defaultValue={isoToInputDate(task?.dueDate ?? "")}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="assigneeId">Atanan</Label>
                <Select name="assigneeId" defaultValue={task?.assigneeId || NONE}>
                  <SelectTrigger id="assigneeId">
                    <SelectValue placeholder="Kimse" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE}>Kimse</SelectItem>
                    {teamMembers.map((m) => (
                      <SelectItem key={m.id} value={m.id}>
                        {m.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
              <Select name="customerId" defaultValue={task?.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>

          <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>
  );
}
