"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Wrench } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input, Field, NativeSelect, Textarea } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/primitives";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogBody, DialogFooter } from "@/components/ui/dialog";
import { MAINTENANCE_CATEGORIES, MAINTENANCE_CATEGORY_LABEL, PRIORITIES, PRIORITY_META } from "@/lib/domain";
import { createMaintenance, updateMaintenance, type MaintenanceInput } from "@/lib/actions/operations";

export interface MaintenanceDialogProps {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  apartments: { id: string; code: string; name: string }[];
  staff: { id: string; fullName: string }[];
  presetApartmentId?: string;
  existing?: { id: string; apartmentId: string; title: string; category: string; priority: string; description: string | null; assigneeId: string | null; cost: number; blocksApartment: boolean; startDate: string | null; completionDate: string | null; status: string };
}

export function MaintenanceDialog({ open, onOpenChange, apartments, staff, presetApartmentId, existing }: MaintenanceDialogProps) {
  const router = useRouter();
  const [busy, setBusy] = React.useState(false);
  const [f, setF] = React.useState({
    apartmentId: existing?.apartmentId ?? presetApartmentId ?? apartments[0]?.id ?? "",
    title: existing?.title ?? "",
    category: existing?.category ?? "GENERAL",
    priority: existing?.priority ?? "MEDIUM",
    description: existing?.description ?? "",
    assigneeId: existing?.assigneeId ?? "",
    cost: String(existing?.cost ?? 0),
    blocksApartment: existing?.blocksApartment ?? false,
    startDate: existing?.startDate?.slice(0, 10) ?? "",
    completionDate: existing?.completionDate?.slice(0, 10) ?? "",
  });
  React.useEffect(() => {
    if (open && existing) setF({ apartmentId: existing.apartmentId, title: existing.title, category: existing.category, priority: existing.priority, description: existing.description ?? "", assigneeId: existing.assigneeId ?? "", cost: String(existing.cost), blocksApartment: existing.blocksApartment, startDate: existing.startDate?.slice(0, 10) ?? "", completionDate: existing.completionDate?.slice(0, 10) ?? "" });
  }, [open, existing]);
  const upd = <K extends keyof typeof f>(k: K, v: (typeof f)[K]) => setF((s) => ({ ...s, [k]: v }));

  async function submit() {
    setBusy(true);
    const payload: MaintenanceInput = { ...f, category: f.category as MaintenanceInput["category"], priority: f.priority as MaintenanceInput["priority"], cost: Number(f.cost) || 0, assigneeId: f.assigneeId || null, startDate: f.startDate || null, completionDate: f.completionDate || null };
    const res = existing ? await updateMaintenance(existing.id, payload) : await createMaintenance(payload);
    setBusy(false);
    if (!res.ok) return toast.error(res.error);
    toast.success(existing ? "Ticket updated" : "Maintenance issue reported");
    onOpenChange(false);
    router.refresh();
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent size="md">
        <DialogHeader>
          <DialogTitle>{existing ? `Edit ${existing.title}` : "Report maintenance issue"}</DialogTitle>
          <DialogDescription>Blocking tickets remove the apartment from the calendar for the given period.</DialogDescription>
        </DialogHeader>
        <DialogBody className="grid gap-4 sm:grid-cols-2">
          <Field label="Apartment" required className="sm:col-span-2">
            <NativeSelect value={f.apartmentId} onChange={(e) => upd("apartmentId", e.target.value)} disabled={!!existing || !!presetApartmentId}>
              {apartments.map((a) => (
                <option key={a.id} value={a.id}>
                  {a.code} {a.name ? `· ${a.name}` : ""}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Issue" required className="sm:col-span-2">
            <Input value={f.title} onChange={(e) => upd("title", e.target.value)} placeholder="Water heater leaking" autoFocus />
          </Field>
          <Field label="Category">
            <NativeSelect value={f.category} onChange={(e) => upd("category", e.target.value)}>
              {MAINTENANCE_CATEGORIES.map((c) => (
                <option key={c} value={c}>
                  {MAINTENANCE_CATEGORY_LABEL[c]}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Priority">
            <NativeSelect value={f.priority} onChange={(e) => upd("priority", e.target.value)}>
              {PRIORITIES.map((p) => (
                <option key={p} value={p}>
                  {PRIORITY_META[p].label}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Description" className="sm:col-span-2">
            <Textarea value={f.description} onChange={(e) => upd("description", e.target.value)} rows={3} />
          </Field>
          <Field label="Assigned to">
            <NativeSelect value={f.assigneeId} onChange={(e) => upd("assigneeId", e.target.value)}>
              <option value="">Unassigned</option>
              {staff.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.fullName}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Estimated / final cost" hint="Added to expenses when completed">
            <Input type="number" min={0} step="10" value={f.cost} onChange={(e) => upd("cost", e.target.value)} suffix="MAD" />
          </Field>
          <label className="flex items-center gap-2 text-sm sm:col-span-2">
            <Checkbox checked={f.blocksApartment} onCheckedChange={(v) => upd("blocksApartment", !!v)} /> Blocks the apartment (unavailable for reservations)
          </label>
          <Field label="Start date">
            <Input type="date" value={f.startDate} onChange={(e) => upd("startDate", e.target.value)} />
          </Field>
          <Field label="Expected completion" hint={f.blocksApartment ? "Required for the block" : undefined}>
            <Input type="date" value={f.completionDate} min={f.startDate} onChange={(e) => upd("completionDate", e.target.value)} />
          </Field>
        </DialogBody>
        <DialogFooter>
          <Button variant="secondary" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button loading={busy} disabled={!f.title.trim() || !f.apartmentId || (f.blocksApartment && !(f.startDate && f.completionDate))} onClick={submit}>
            <Wrench /> {existing ? "Save" : "Report issue"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
