"use client";

import { useActionState, useEffect } from "react";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ResponsiveSheet, FormWizard } from "@/components/ui/responsive-sheet";
import { createCustomerSearchAction, updateCustomerSearchAction } from "@/lib/appwrite/customer-search-actions";
import type { Customer, CustomerSearch } from "@/lib/appwrite/schema";

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

const WEIGHT_OPTIONS = [
  { value: "1", label: "1 — Önemsiz" },
  { value: "2", label: "2 — Az önemli" },
  { value: "3", label: "3 — Orta" },
  { value: "4", label: "4 — Önemli" },
  { value: "5", label: "5 — Çok önemli" },
];

function WeightSelect({ name, defaultValue }: { name: string; defaultValue?: number | null }) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-muted-foreground text-xs shrink-0">Önem:</span>
      <select name={name} defaultValue={String(defaultValue ?? 3)}
        className="border-input bg-background h-8 rounded-md border px-2 text-xs">
        {WEIGHT_OPTIONS.map((o) => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>
    </div>
  );
}

function parseJsonToInput(json?: string | null): string {
  if (!json) return "";
  try { return (JSON.parse(json) as string[]).join(", "); } catch { return json; }
}

interface SearchFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  search?: CustomerSearch | null;
  customers: Customer[];
  defaultCustomerId?: string;
  onSuccess?: () => void;
}

export function SearchFormSheet({ open, onOpenChange, search, customers, defaultCustomerId, onSuccess }: SearchFormSheetProps) {
  const action = search ? updateCustomerSearchAction.bind(null, search.$id) : createCustomerSearchAction;
  const [state, formAction, isPending] = useActionState(action, INITIAL);

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

  const fe = state.fieldErrors ?? {};

  const steps = [
    {
      label: "Müşteri",
      content: (
        <>
          <div className="grid gap-1.5">
            <Label>Müşteri *</Label>
            <select name="customerId" defaultValue={search?.customerId ?? defaultCustomerId ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="">Müşteri seçin</option>
              {customers.map((c) => (
                <option key={c.$id} value={c.$id}>{c.name}</option>
              ))}
            </select>
            {fe.customerId && <p className="text-destructive text-xs">{fe.customerId[0]}</p>}
          </div>
          <div className="grid gap-1.5">
            <Label>İlan türü</Label>
            <select name="listingType" defaultValue={search?.listingType ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="">Tümü</option>
              <option value="satilik">Satılık</option>
              <option value="kiralik">Kiralık</option>
            </select>
          </div>
        </>
      ),
    },
    {
      label: "Emlak & Boyut",
      content: (
        <div className="grid grid-cols-2 gap-x-5 gap-y-4">
          <div className="grid gap-1.5">
            <Label>Emlak tipleri</Label>
            <Input name="propertyTypes" defaultValue={parseJsonToInput(search?.propertyTypes)} placeholder="daire, villa" />
            <WeightSelect name="propertyTypeWeight" defaultValue={search?.propertyTypeWeight} />
          </div>
          <div className="grid gap-1.5">
            <Label>Oda sayıları</Label>
            <Input name="roomCounts" defaultValue={parseJsonToInput(search?.roomCounts)} placeholder="2+1, 3+1" />
            <WeightSelect name="roomCountWeight" defaultValue={search?.roomCountWeight} />
          </div>
          <div className="grid gap-1.5">
            <Label>Fiyat aralığı</Label>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <span className="text-muted-foreground text-xs block mb-1">Min</span>
                <Input name="minPrice" type="number" min="0" defaultValue={search?.minPrice ?? ""} placeholder="0" />
              </div>
              <div>
                <span className="text-muted-foreground text-xs block mb-1">Max</span>
                <Input name="maxPrice" type="number" min="0" defaultValue={search?.maxPrice ?? ""} placeholder="—" />
              </div>
            </div>
            <WeightSelect name="priceWeight" defaultValue={search?.priceWeight} />
          </div>
          <div className="grid gap-1.5">
            <Label>m² aralığı</Label>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <span className="text-muted-foreground text-xs block mb-1">Min</span>
                <Input name="minM2" type="number" min="0" defaultValue={search?.minM2 ?? ""} placeholder="0" />
              </div>
              <div>
                <span className="text-muted-foreground text-xs block mb-1">Max</span>
                <Input name="maxM2" type="number" min="0" defaultValue={search?.maxM2 ?? ""} placeholder="—" />
              </div>
            </div>
            <WeightSelect name="m2Weight" defaultValue={search?.m2Weight} />
          </div>
        </div>
      ),
    },
    {
      label: "Konum",
      content: (
        <>
          <div className="grid gap-1.5">
            <Label>Şehirler</Label>
            <Input name="cities" defaultValue={parseJsonToInput(search?.cities)} placeholder="İstanbul, Ankara" />
            <WeightSelect name="locationWeight" defaultValue={search?.locationWeight} />
          </div>
          <div className="grid gap-1.5">
            <Label>İlçeler</Label>
            <Input name="districts" defaultValue={parseJsonToInput(search?.districts)} placeholder="Kadıköy, Beşiktaş" />
          </div>
          <div className="grid gap-1.5">
            <Label>Notlar</Label>
            <Textarea name="notes" rows={3} defaultValue={search?.notes ?? ""} />
          </div>
        </>
      ),
    },
  ];

  return (
    <ResponsiveSheet open={open} onOpenChange={onOpenChange}
      title={search ? "Aramayı Düzenle" : "Yeni Arama Kriteri"}
      maxWidth="sm:max-w-xl">
      <form action={formAction}>
        <FormWizard steps={steps} isPending={isPending} submitLabel={search ? "Güncelle" : "Oluştur"} />
      </form>
    </ResponsiveSheet>
  );
}
