"use client";

import { useActionState, useEffect } from "react";
import { CircleNotch } from '@/lib/icons';
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import {
  createPresentationAction,
  updatePresentationAction,
} from "@/lib/appwrite/presentation-actions";
import type { Customer, Presentation, Property } from "@/lib/appwrite/schema";

type ActionState = { ok: boolean; error?: string; fieldErrors?: Record<string, string[]>; id?: string };
const INITIAL: ActionState = { ok: false };

interface PresentationFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  presentation?: Presentation | null;
  customers: Customer[];
  properties: Property[];
  onSuccess?: () => void;
}

export function PresentationFormSheet({
  open,
  onOpenChange,
  presentation,
  customers,
  properties,
  onSuccess,
}: PresentationFormSheetProps) {
  const action = presentation
    ? updatePresentationAction.bind(null, presentation.$id)
    : createPresentationAction;

  const [state, formAction, isPending] = useActionState(action, INITIAL);

  const selectedIds: string[] = presentation
    ? (JSON.parse(presentation.propertyIds || "[]") as string[])
    : [];

  useEffect(() => {
    if (state.ok) {
      toast.success(presentation ? "Sunum güncellendi." : "Sunum oluşturuldu.");
      onSuccess?.();
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  const fe = state.fieldErrors ?? {};

  return (
    <ResponsiveSheet
      open={open}
      onOpenChange={onOpenChange}
      title={presentation ? "Sunumu Düzenle" : "Yeni Sunum"}
    >
      <form action={formAction} className="space-y-4 pb-2">
        <div data-tour="form-presentations-title" className="grid gap-1.5">
          <Label htmlFor="title">Sunum başlığı *</Label>
          <Input id="title" name="title" defaultValue={presentation?.title} placeholder="Kadıköy 3+1 Seçenekleri" />
          {fe.title && <p className="text-destructive text-xs">{fe.title[0]}</p>}
        </div>

        <div className="grid gap-1.5">
          <Label>Müşteri</Label>
          <select
            name="customerId"
            defaultValue={presentation?.customerId ?? ""}
            className="border-input bg-background h-9 rounded-md border px-3 text-sm"
          >
            <option value="">Müşteri seçin (opsiyonel)</option>
            {customers.map((c) => (
              <option key={c.$id} value={c.$id}>{c.name}</option>
            ))}
          </select>
        </div>

        <div data-tour="form-presentations-properties" className="grid gap-1.5">
          <Label>İlanlar *</Label>
          {fe.propertyIds && <p className="text-destructive text-xs">{fe.propertyIds[0]}</p>}
          <PropertyCheckboxList properties={properties} selectedIds={selectedIds} />
        </div>

        <div className="grid gap-1.5">
          <Label htmlFor="expiresAt">Geçerlilik tarihi</Label>
          <Input
            id="expiresAt"
            name="expiresAt"
            type="date"
            defaultValue={presentation?.expiresAt ? presentation.expiresAt.split("T")[0] : ""}
          />
        </div>

        <div className="grid gap-1.5">
          <Label htmlFor="notes">Notlar</Label>
          <Textarea id="notes" name="notes" rows={2} defaultValue={presentation?.notes ?? ""} />
        </div>

        <div className="pt-2">
          <Button type="submit" disabled={isPending} className="w-full">
            {isPending && <CircleNotch className="mr-2 size-4 animate-spin" />}
            {presentation ? "Güncelle" : "Oluştur"}
          </Button>
        </div>
      </form>
    </ResponsiveSheet>
  );
}

function PropertyCheckboxList({
  properties,
  selectedIds,
}: {
  properties: Property[];
  selectedIds: string[];
}) {
  return (
    <div className="max-h-48 overflow-y-auto rounded-md border p-2 space-y-1">
      {properties.length === 0 && (
        <p className="text-muted-foreground text-sm">Aktif ilan bulunamadı.</p>
      )}
      {properties.map((p) => (
        <label key={p.$id} className="flex items-center gap-2 cursor-pointer rounded px-2 py-1 hover:bg-muted/50">
          <Checkbox
            name="propertyIdsRaw"
            value={p.$id}
            defaultChecked={selectedIds.includes(p.$id)}
          />
          <span className="text-sm truncate">
            {p.title} — {p.city}{p.district ? `, ${p.district}` : ""}
          </span>
        </label>
      ))}
    </div>
  );
}
