"use client";

import { useActionState, useEffect, useState } from "react";
import { Loader2, Save, Trash2 } 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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import {
  createCalendarEventAction,
  updateCalendarEventAction,
} from "@/lib/appwrite/calendar-actions";
import { initialCalendarState } from "@/lib/appwrite/calendar-types";
import { cn } from "@/lib/utils";

import { COLOR_PRESETS, type Customer, type EventRow } from "./types";

const NONE = "__none__";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  event?: EventRow | null;
  defaultDate?: string; // YYYY-MM-DD for new events
  customers: Customer[];
  onRequestDelete?: (event: EventRow) => void;
};

function isoToInput(iso: string, allDay: boolean): string {
  if (!iso) return "";
  if (allDay) return iso.slice(0, 10);
  const d = new Date(iso);
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function EventFormSheet({
  open,
  onOpenChange,
  event,
  defaultDate,
  customers,
  onRequestDelete,
}: Props) {
  const isEdit = Boolean(event);
  const action = isEdit ? updateCalendarEventAction : createCalendarEventAction;
  const [state, formAction, isPending] = useActionState(action, initialCalendarState);
  const [allDay, setAllDay] = useState<boolean>(event?.allDay ?? false);

  useEffect(() => {
    setAllDay(event?.allDay ?? false);
  }, [event]);

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

  const startDefault =
    event?.start
      ? isoToInput(event.start, allDay)
      : defaultDate
        ? allDay
          ? defaultDate
          : `${defaultDate}T09:00`
        : "";
  const endDefault =
    event?.end
      ? isoToInput(event.end, allDay)
      : defaultDate
        ? allDay
          ? defaultDate
          : `${defaultDate}T10:00`
        : "";

  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 ? "Etkinliği düzenle" : "Yeni etkinlik"}</SheetTitle>
          <SheetDescription>
            Tarih, saat ve müşteri bilgileri ile bir takvim girdisi oluşturun.
          </SheetDescription>
        </SheetHeader>

        <form
          action={(fd) => {
            ["customerId", "color"].forEach((k) => {
              if (fd.get(k) === NONE) fd.set(k, "");
            });
            formAction(fd);
          }}
          className="flex flex-1 flex-col"
        >
          {isEdit && event && <input type="hidden" name="id" value={event.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={event?.title ?? ""}
                placeholder="Örn. Müşteri toplantısı"
                required
              />
              {state.fieldErrors?.title && (
                <p className="text-destructive text-xs">{state.fieldErrors.title}</p>
              )}
            </div>

            <div className="flex items-center justify-between rounded-md border p-3">
              <div className="grid gap-0.5">
                <Label htmlFor="allDay" className="cursor-pointer">
                  Tüm gün
                </Label>
                <p className="text-muted-foreground text-xs">Saat girmeden gün boyu sürecek.</p>
              </div>
              <Switch
                id="allDay"
                name="allDay"
                checked={allDay}
                onCheckedChange={setAllDay}
              />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="start">Başlangıç *</Label>
                <Input
                  id="start"
                  name="start"
                  type={allDay ? "date" : "datetime-local"}
                  defaultValue={startDefault}
                  required
                />
                {state.fieldErrors?.start && (
                  <p className="text-destructive text-xs">{state.fieldErrors.start}</p>
                )}
              </div>
              <div className="grid gap-2">
                <Label htmlFor="end">Bitiş *</Label>
                <Input
                  id="end"
                  name="end"
                  type={allDay ? "date" : "datetime-local"}
                  defaultValue={endDefault}
                  required
                />
                {state.fieldErrors?.end && (
                  <p className="text-destructive text-xs">{state.fieldErrors.end}</p>
                )}
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
              <Select name="customerId" defaultValue={event?.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="color">Renk</Label>
              <Select name="color" defaultValue={event?.color || NONE}>
                <SelectTrigger id="color">
                  <SelectValue placeholder="Varsayılan" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={NONE}>Varsayılan</SelectItem>
                  {COLOR_PRESETS.map((c) => (
                    <SelectItem key={c.value} value={c.value}>
                      <span className="flex items-center gap-2">
                        <span className={cn("size-3 rounded-full", c.classes)} />
                        {c.label}
                      </span>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="description">Notlar</Label>
              <Textarea
                id="description"
                name="description"
                rows={3}
                defaultValue={event?.description ?? ""}
                placeholder="Açıklama, gündem, 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 && event && onRequestDelete && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="text-destructive hover:text-destructive"
                    onClick={() => onRequestDelete(event)}
                    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>
    </Sheet>
  );
}
