"use client";

import { useActionState, useEffect, useState } from "react";
import { ChevronDown, Loader2, Save } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
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 {
  createLeadAction,
  updateLeadAction,
} from "@/lib/appwrite/lead-actions";
import { initialLeadState } from "@/lib/appwrite/lead-types";

import { LEAD_SOURCE_LABEL, LEAD_STATUS_CONFIG, type LeadRow, type MemberOption } from "./types";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  lead?: LeadRow | null;
  defaultStatus?: string;
  members: MemberOption[];
  onCreated?: (leadId: string) => void;
};

export function LeadFormSheet({ open, onOpenChange, lead, defaultStatus, members, onCreated }: Props) {
  const isEdit = Boolean(lead);
  const action = isEdit ? updateLeadAction : createLeadAction;
  const [state, formAction, isPending] = useActionState(action, initialLeadState);
  const [assigneeOpen, setAssigneeOpen] = useState(false);
  const [assigneeId, setAssigneeId] = useState(lead?.assigneeId ?? "");

  useEffect(() => {
    if (open) setAssigneeId(lead?.assigneeId ?? "");
  }, [open, lead]);

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

  const selectedMember = members.find((m) => m.id === assigneeId);

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-lg">
        <SheetHeader className="border-b px-6 py-4">
          <SheetTitle>{isEdit ? "Adayı düzenle" : "Yeni müşteri adayı"}</SheetTitle>
          <SheetDescription>Müşteri adayının bilgilerini girin.</SheetDescription>
        </SheetHeader>

        <form action={formAction} className="flex flex-1 flex-col">
          {isEdit && lead && <input type="hidden" name="id" value={lead.id} />}
          <input type="hidden" name="assigneeId" value={assigneeId} />

          <div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
            {/* Ad / Şirket */}
            <div className="grid gap-2">
              <Label htmlFor="name">Şirket / Lead adı *</Label>
              <Input id="name" name="name" defaultValue={lead?.name ?? ""} placeholder="Örn. ABC Yazılım A.Ş." required />
              {state.fieldErrors?.name && <p className="text-destructive text-xs">{state.fieldErrors.name}</p>}
            </div>

            {/* İlgili kişi */}
            <div className="grid gap-2">
              <Label htmlFor="contactName">İlgili kişi</Label>
              <Input id="contactName" name="contactName" defaultValue={lead?.contactName ?? ""} placeholder="Ad Soyad" />
            </div>

            {/* Tel + Email */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="phone">Telefon</Label>
                <Input id="phone" name="phone" type="tel" defaultValue={lead?.phone ?? ""} placeholder="+90 5xx xxx xx xx" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="email">E-posta</Label>
                <Input id="email" name="email" type="email" defaultValue={lead?.email ?? ""} placeholder="ornek@sirket.com" />
                {state.fieldErrors?.email && <p className="text-destructive text-xs">{state.fieldErrors.email}</p>}
              </div>
            </div>

            {/* Kaynak + Durum */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="source">Kaynak</Label>
                <Select name="source" defaultValue={lead?.source ?? "other"}>
                  <SelectTrigger id="source"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {(Object.entries(LEAD_SOURCE_LABEL) as [string, string][]).map(([v, l]) => (
                      <SelectItem key={v} value={v}>{l}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="status">Durum</Label>
                <Select name="status" defaultValue={lead?.status ?? defaultStatus ?? "cold"}>
                  <SelectTrigger id="status"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {(Object.entries(LEAD_STATUS_CONFIG) as [string, { label: string }][]).map(([v, c]) => (
                      <SelectItem key={v} value={v}>{c.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Tahmini değer + para birimi */}
            <div className="grid gap-4 sm:grid-cols-3">
              <div className="grid gap-2 sm:col-span-2">
                <Label htmlFor="estimatedValue">Tahmini değer</Label>
                <Input id="estimatedValue" name="estimatedValue" type="number" step="0.01" min="0"
                  defaultValue={lead?.estimatedValue ?? ""} placeholder="0.00" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="currency">Para birimi</Label>
                <Select name="currency" defaultValue={lead?.currency ?? "TRY"}>
                  <SelectTrigger id="currency"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="TRY">₺ TRY</SelectItem>
                    <SelectItem value="USD">$ USD</SelectItem>
                    <SelectItem value="EUR">€ EUR</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Sorumlu */}
            {members.length > 0 && (
              <div className="grid gap-2">
                <Label>Sorumlu</Label>
                <Popover open={assigneeOpen} onOpenChange={setAssigneeOpen}>
                  <PopoverTrigger asChild>
                    <Button type="button" variant="outline" className="w-full justify-between">
                      {selectedMember ? (
                        <Badge variant="secondary" className="font-normal">{selectedMember.name}</Badge>
                      ) : (
                        <span className="text-muted-foreground text-sm font-normal">Personel seçin</span>
                      )}
                      <ChevronDown className="text-muted-foreground size-4" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-64 p-1" align="start">
                    <label className="flex cursor-pointer items-center gap-3 rounded px-3 py-2 hover:bg-muted">
                      <Checkbox checked={!assigneeId} onCheckedChange={() => { setAssigneeId(""); setAssigneeOpen(false); }} />
                      <span className="text-muted-foreground text-sm">Atanmamış</span>
                    </label>
                    {members.map((m) => (
                      <label key={m.id} className="flex cursor-pointer items-center gap-3 rounded px-3 py-2 hover:bg-muted">
                        <Checkbox checked={assigneeId === m.id} onCheckedChange={() => { setAssigneeId(m.id); setAssigneeOpen(false); }} />
                        <div className="min-w-0">
                          <div className="truncate text-sm font-medium">{m.name}</div>
                          <div className="text-muted-foreground truncate text-xs">{m.email}</div>
                        </div>
                      </label>
                    ))}
                  </PopoverContent>
                </Popover>
              </div>
            )}

            {/* Notlar */}
            <div className="grid gap-2">
              <Label htmlFor="notes">Notlar</Label>
              <Textarea id="notes" name="notes" rows={3} defaultValue={lead?.notes ?? ""} placeholder="İlk görüşme notları, ihtiyaçlar vb." />
            </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>
  );
}
