"use client";

import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { TriangleAlert } from "lucide-react";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Field } from "@/components/shared/field";
import { FormDialog } from "@/components/shared/form-dialog";
import { StatusBadge } from "@/components/shared/status-badge";
import { useChangeCustomerStatus } from "@/hooks/use-customers";
import { applyServerErrors, getErrorMessage } from "@/lib/api";
import { CUSTOMER_STATUS_LABELS, TECHNICIAN_STATUSES } from "@/lib/constants";
import { todayISO } from "@/lib/format";
import type { Customer, CustomerStatus, Role } from "@/types";

const schema = z.object({
  status: z.string().min(1, "Pilih status baru."),
  date: z.string().min(1, "Tanggal wajib diisi."),
  reason: z.string().max(255),
});
type FormValues = z.infer<typeof schema>;

export function StatusDialog({ customer, role, open, onOpenChange }: { customer: Customer; role: Role; open: boolean; onOpenChange: (v: boolean) => void }) {
  const mutation = useChangeCustomerStatus(customer.id);
  const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { status: "", date: todayISO(), reason: "" } });

  useEffect(() => {
    if (open) form.reset({ status: "", date: todayISO(), reason: "" });
  }, [open, form]);

  const allowed = (Object.keys(CUSTOMER_STATUS_LABELS) as CustomerStatus[]).filter(
    (s) => s !== customer.status && (role === "admin" || TECHNICIAN_STATUSES.includes(s)),
  );
  const selected = form.watch("status");

  async function onSubmit(values: FormValues) {
    try {
      const res = await mutation.mutateAsync({ status: values.status as CustomerStatus, date: values.date, reason: values.reason || null });
      toast.success(res.message ?? "Status diubah.");
      onOpenChange(false);
    } catch (err) {
      if (!applyServerErrors(err, form.setError)) toast.error(getErrorMessage(err));
    }
  }

  return (
    <FormDialog
      open={open}
      onOpenChange={onOpenChange}
      title="Ubah Status Pelanggan"
      description={<span className="flex items-center gap-2">Status saat ini: <StatusBadge type="customer" status={customer.status} /></span>}
      onSubmit={form.handleSubmit(onSubmit)}
      submitting={form.formState.isSubmitting}
    >
      <Field label="Status baru" required error={form.formState.errors.status?.message}>
        <Controller control={form.control} name="status" render={({ field }) => (
          <Select value={field.value} onValueChange={field.onChange}>
            <SelectTrigger><SelectValue placeholder="Pilih status" /></SelectTrigger>
            <SelectContent>
              {allowed.map((s) => <SelectItem key={s} value={s}>{CUSTOMER_STATUS_LABELS[s]}</SelectItem>)}
            </SelectContent>
          </Select>
        )} />
      </Field>
      <Field label="Tanggal berlaku" htmlFor="status-date" required error={form.formState.errors.date?.message}>
        <Input id="status-date" type="date" {...form.register("date")} />
      </Field>
      <Field label="Alasan / keterangan" htmlFor="status-reason" error={form.formState.errors.reason?.message}>
        <Input id="status-reason" placeholder="Contoh: pindah rumah, menunggak 3 bulan" {...form.register("reason")} />
      </Field>
      {selected === "berhenti" && (
        <div className="flex gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
          <TriangleAlert className="mt-0.5 h-4 w-4 shrink-0" />
          Tagihan bulan-bulan setelah tanggal berhenti yang belum dibayar sama sekali akan otomatis dibatalkan.
        </div>
      )}
    </FormDialog>
  );
}
