"use client";

import { useActionState, useEffect, useState } from "react";
import { Check, ChevronDown, Loader2, Save, Users } 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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import {
  createServiceAction,
  updateServiceAction,
} from "@/lib/appwrite/service-actions";
import { initialServiceState } from "@/lib/appwrite/service-types";
import { AttachmentsPanel } from "@/components/attachments-panel";
import type { CustomerOption, MemberOption, ServiceRow } from "./types";

const PRESET_SERVICES = [
  "Web sitesi tasarımı",
  "Web sitesi bakımı",
  "SEO optimizasyonu",
  "Sosyal medya yönetimi",
  "Domain kayıt / yenileme",
  "Hosting hizmeti",
  "Kurumsal e-posta",
  "Grafik tasarım",
  "Logo tasarımı",
  "Google Ads yönetimi",
  "Meta Ads yönetimi",
  "Yazılım geliştirme",
  "Mobil uygulama",
  "Teknik destek",
  "Muhasebe danışmanlığı",
  "Eğitim / danışmanlık",
];

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  service?: ServiceRow | null;
  customers: CustomerOption[];
  defaultCustomerId?: string;
  members: MemberOption[];
};

export function ServiceFormSheet({
  open,
  onOpenChange,
  service,
  customers,
  defaultCustomerId,
  members,
}: Props) {
  const isEdit = Boolean(service);
  const action = isEdit ? updateServiceAction : createServiceAction;
  const [state, formAction, isPending] = useActionState(action, initialServiceState);

  const [name, setName] = useState(service?.name ?? "");
  const [assigneeIds, setAssigneeIds] = useState<string[]>(service?.assigneeIds ?? []);
  const [assigneeOpen, setAssigneeOpen] = useState(false);

  // Reset local state when sheet opens with a different service
  useEffect(() => {
    if (open) {
      setName(service?.name ?? "");
      setAssigneeIds(service?.assigneeIds ?? []);
    }
  }, [open, service]);

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

  const toggleAssignee = (id: string) => {
    setAssigneeIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
    );
  };

  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 ? "Hizmeti düzenle" : "Yeni hizmet"}</SheetTitle>
          <SheetDescription>
            {customers.length === 0
              ? "Hizmet eklemek için önce en az bir müşteri tanımlamalısınız."
              : "Müşteriye sunduğunuz hizmeti tanımlayın."}
          </SheetDescription>
        </SheetHeader>

        <form action={formAction} className="flex flex-1 flex-col">
          {isEdit && service && <input type="hidden" name="id" value={service.id} />}
          {/* Assignee hidden inputs — one per selected member */}
          {assigneeIds.map((id) => (
            <input key={id} type="hidden" name="assigneeIds" value={id} />
          ))}

          <div className="flex-1 space-y-5 overflow-y-auto px-6 py-5">
            {/* Müşteri */}
            <div className="grid gap-2">
              <Label htmlFor="customerId">Müşteri *</Label>
              <Select
                name="customerId"
                defaultValue={service?.customerId ?? defaultCustomerId ?? ""}
                disabled={customers.length === 0}
              >
                <SelectTrigger id="customerId">
                  <SelectValue placeholder="Müşteri seçin" />
                </SelectTrigger>
                <SelectContent>
                  {customers.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {state.fieldErrors?.customerId && (
                <p className="text-destructive text-xs">{state.fieldErrors.customerId}</p>
              )}
            </div>

            {/* Hizmet adı + hazır şablonlar */}
            <div className="grid gap-2">
              <Label htmlFor="name">Hizmet adı *</Label>
              {/* Preset chips */}
              <div className="flex flex-wrap gap-1.5">
                {PRESET_SERVICES.map((preset) => (
                  <button
                    key={preset}
                    type="button"
                    onClick={() => setName(preset)}
                    className={cn(
                      "rounded-full border px-2.5 py-0.5 text-xs transition-colors",
                      name === preset
                        ? "border-primary bg-primary text-primary-foreground"
                        : "border-border bg-muted/40 text-muted-foreground hover:border-primary/50 hover:text-foreground",
                    )}
                  >
                    {preset}
                  </button>
                ))}
              </div>
              <Input
                id="name"
                name="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Hizmet adını yazın veya yukarıdan seçin"
                required
              />
              {state.fieldErrors?.name && (
                <p className="text-destructive text-xs">{state.fieldErrors.name}</p>
              )}
            </div>

            {/* Açıklama */}
            <div className="grid gap-2">
              <Label htmlFor="description">Açıklama</Label>
              <Textarea
                id="description"
                name="description"
                rows={3}
                defaultValue={service?.description ?? ""}
                placeholder="Hizmetin kapsamı, sınırları, vb."
              />
            </div>

            {/* Fiyat + Para birimi */}
            <div className="grid gap-4 sm:grid-cols-3">
              <div className="grid gap-2 sm:col-span-2">
                <Label htmlFor="unitPrice">Birim fiyat *</Label>
                <Input
                  id="unitPrice"
                  name="unitPrice"
                  type="number"
                  step="0.01"
                  min="0"
                  defaultValue={service?.unitPrice ?? ""}
                  placeholder="0.00"
                  required
                />
                {state.fieldErrors?.unitPrice && (
                  <p className="text-destructive text-xs">{state.fieldErrors.unitPrice}</p>
                )}
              </div>
              <div className="grid gap-2">
                <Label htmlFor="currency">Para birimi</Label>
                <Select name="currency" defaultValue={service?.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>

            {/* Faturalama dönemi + Tekrarlayan */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="billingPeriod">Faturalama dönemi</Label>
                <Select
                  name="billingPeriod"
                  defaultValue={service?.billingPeriod ?? "onetime"}
                >
                  <SelectTrigger id="billingPeriod">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="onetime">Tek seferlik</SelectItem>
                    <SelectItem value="monthly">Aylık</SelectItem>
                    <SelectItem value="yearly">Yıllık</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-end pb-0.5">
                <div className="flex w-full items-center justify-between rounded-md border p-3">
                  <Label htmlFor="recurring" className="cursor-pointer text-sm">
                    Tekrarlayan
                  </Label>
                  <Switch
                    id="recurring"
                    name="recurring"
                    defaultChecked={service?.recurring}
                  />
                </div>
              </div>
            </div>

            {/* Ekler */}
            {isEdit && service && (
              <AttachmentsPanel entityType="service" entityId={service.id} />
            )}

            {/* Sorumlu personel */}
            {members.length > 0 && (
              <div className="grid gap-2">
                <Label>Sorumlu personel</Label>
                <Popover open={assigneeOpen} onOpenChange={setAssigneeOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      type="button"
                      variant="outline"
                      className="h-auto min-h-10 w-full justify-between px-3 py-2"
                    >
                      <div className="flex flex-wrap gap-1">
                        {assigneeIds.length === 0 ? (
                          <span className="text-muted-foreground text-sm font-normal">
                            Personel seçin (isteğe bağlı)
                          </span>
                        ) : (
                          assigneeIds.map((id) => {
                            const m = members.find((x) => x.id === id);
                            return (
                              <Badge key={id} variant="secondary" className="font-normal">
                                {m?.name ?? id}
                              </Badge>
                            );
                          })
                        )}
                      </div>
                      <ChevronDown className="text-muted-foreground ml-2 size-4 shrink-0" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-64 p-1" align="start">
                    {members.map((m) => {
                      const checked = assigneeIds.includes(m.id);
                      return (
                        <label
                          key={m.id}
                          className="flex cursor-pointer items-center gap-3 rounded px-3 py-2 hover:bg-muted"
                        >
                          <Checkbox
                            checked={checked}
                            onCheckedChange={() => toggleAssignee(m.id)}
                          />
                          <div className="flex-1 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>
                          {checked && <Check className="text-primary size-3.5 shrink-0" />}
                        </label>
                      );
                    })}
                  </PopoverContent>
                </Popover>
              </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 || customers.length === 0}>
                {isPending ? (
                  <>
                    <Loader2 className="size-4 animate-spin" />
                    Kaydediliyor...
                  </>
                ) : (
                  <>
                    <Save className="size-4" />
                    {isEdit ? "Güncelle" : "Kaydet"}
                  </>
                )}
              </Button>
            </div>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
