"use client";

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

import { ResponsiveSheet, FormWizard } from "@/components/ui/responsive-sheet";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createDealAction, updateDealAction } from "@/lib/appwrite/deal-actions";
import type { Customer, Deal } from "@/lib/appwrite/schema";

interface DealFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  deal?: Deal | null;
  customers: Customer[];
  onSuccess: () => void;
}

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

export function DealFormSheet({ open, onOpenChange, deal, customers, onSuccess }: DealFormSheetProps) {
  const action = deal ? updateDealAction.bind(null, deal.$id) : createDealAction;
  const [state, dispatch, isPending] = useActionState(action, EMPTY_STATE);

  useEffect(() => {
    if (state.ok) {
      toast.success(deal ? "İşlem güncellendi." : "İşlem kaydedildi.");
      onSuccess();
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    startTransition(() => dispatch(fd));
  }

  const steps = [
    {
      label: "İşlem",
      content: (
        <>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1.5">
              <Label>Tip</Label>
              <Select name="type" defaultValue={deal?.type ?? "satis"} required>
                <SelectTrigger><SelectValue placeholder="Seç" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="satis">Satış</SelectItem>
                  <SelectItem value="kiralama">Kiralama</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-1.5">
              <Label>İlan Başlığı</Label>
              <Input name="propertyTitle" placeholder="İsteğe bağlı" defaultValue={deal?.propertyTitle ?? ""} />
            </div>
          </div>
          <div className="grid gap-1.5">
            <Label>Müşteri</Label>
            <select
              name="customerId"
              defaultValue={deal?.customerId ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm"
            >
              <option value="">— Seçiniz (opsiyonel)</option>
              {customers.map((c) => (
                <option key={c.$id} value={c.$id}>{c.name}</option>
              ))}
            </select>
          </div>
          <div className="grid gap-1.5">
            <Label>Satış / Kira Bedeli (₺)</Label>
            <Input name="salePrice" type="number" min={0} step="any" required placeholder="0"
              defaultValue={deal?.salePrice ?? ""} />
            {state.fieldErrors?.salePrice && (
              <p className="text-destructive text-xs">{state.fieldErrors.salePrice[0]}</p>
            )}
          </div>
        </>
      ),
    },
    {
      label: "Komisyon",
      content: (
        <div className="flex flex-col gap-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1.5">
              <Label>Oran (%)</Label>
              <Input name="commissionRate" type="number" min={0} max={100} step="any" required placeholder="3"
                defaultValue={deal?.commissionRate ?? ""} />
            </div>
            <div className="grid gap-1.5">
              <Label>Tutar (₺)</Label>
              <Input name="commissionAmount" type="number" min={0} step="any" required placeholder="0"
                defaultValue={deal?.commissionAmount ?? ""} />
            </div>
            <div className="grid gap-1.5">
              <Label>Ofis payı (%)</Label>
              <Input name="officeSharePercent" type="number" min={0} max={100} step="any" placeholder="50"
                defaultValue={deal?.officeSharePercent ?? ""} />
            </div>
            <div className="grid gap-1.5">
              <Label>Danışman payı (%)</Label>
              <Input name="agentSharePercent" type="number" min={0} max={100} step="any" placeholder="50"
                defaultValue={deal?.agentSharePercent ?? ""} />
            </div>
          </div>

          <div className="border-t pt-4">
            <p className="text-xs font-medium text-muted-foreground mb-3">Referans / Ortak Danışman</p>
            <div className="grid grid-cols-2 gap-3">
              <div className="grid gap-1.5 col-span-2">
                <Label>Ad Soyad</Label>
                <Input name="referralName" placeholder="Ahmet Yılmaz (opsiyonel)"
                  defaultValue={deal?.referralName ?? ""} />
              </div>
              <div className="grid gap-1.5">
                <Label>Telefon</Label>
                <Input name="referralPhone" placeholder="05xx xxx xx xx"
                  defaultValue={deal?.referralPhone ?? ""} />
              </div>
              <div className="grid gap-1.5">
                <Label>Komisyondan pay (%)</Label>
                <Input name="referralPercent" type="number" min={0} max={100} step="any"
                  placeholder="örn. 25"
                  defaultValue={deal?.referralPercent ?? ""} />
              </div>
            </div>
          </div>
        </div>
      ),
    },
    {
      label: "Kapanış",
      content: (
        <>
          <div className="grid gap-1.5">
            <Label>Kapanış Tarihi</Label>
            <Input name="closingDate" type="date"
              defaultValue={deal?.closingDate ? deal.closingDate.slice(0, 10) : ""} />
          </div>
          <div className="grid gap-1.5">
            <Label>Notlar</Label>
            <Textarea name="notes" rows={4} placeholder="Opsiyonel notlar..." defaultValue={deal?.notes ?? ""} />
          </div>
        </>
      ),
    },
  ];

  return (
    <ResponsiveSheet open={open} onOpenChange={onOpenChange}
      title={deal ? "İşlemi Düzenle" : "Yeni İşlem"}
      maxWidth="sm:max-w-lg">
      <form onSubmit={handleSubmit}>
        <FormWizard steps={steps} isPending={isPending} submitLabel={deal ? "Güncelle" : "Kaydet"} />
      </form>
    </ResponsiveSheet>
  );
}
