"use client";

import { useRef } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Camera, Loader2, X } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { CurrencyInput } from "@/components/shared/currency-input";
import { Field } from "@/components/shared/field";
import { useCreatePayment } from "@/hooks/use-billing";
import { applyServerErrors, getErrorMessage } from "@/lib/api";
import { PAYMENT_METHOD_LABELS } from "@/lib/constants";
import { formatRupiah, todayISO } from "@/lib/format";
import { cn } from "@/lib/utils";
import type { ApiResponse, PaymentDetail, PaymentMethod, WaMeta } from "@/types";

const METHODS = Object.keys(PAYMENT_METHOD_LABELS) as PaymentMethod[];

interface PaymentFormProps {
  invoice: { id: number; remaining: number };
  onSuccess: (res: ApiResponse<PaymentDetail, WaMeta>) => void;
  submitLabel?: string;
}

/** Form input pembayaran: nominal default = sisa tagihan; bisa bayar sebagian. */
export function PaymentForm({ invoice, onSuccess, submitLabel = "Simpan Pembayaran" }: PaymentFormProps) {
  const create = useCreatePayment();
  const fileRef = useRef<HTMLInputElement>(null);
  const today = todayISO();

  const schema = z.object({
    amount: z
      .number({ invalid_type_error: "Nominal wajib diisi.", required_error: "Nominal wajib diisi." })
      .int()
      .min(1, "Nominal wajib diisi.")
      .max(invoice.remaining, `Melebihi sisa tagihan (${formatRupiah(invoice.remaining)}).`),
    paid_at: z.string().min(1, "Tanggal wajib diisi.").refine((v) => v <= today, "Tanggal bayar tidak boleh melebihi hari ini."),
    method: z.enum(["tunai", "transfer", "potong_pupuk", "potong_gaji", "lainnya"]),
    notes: z.string().max(500),
    proof: z.instanceof(File).nullable(),
  });
  type FormValues = z.infer<typeof schema>;

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: { amount: invoice.remaining, paid_at: today, method: "tunai", notes: "", proof: null },
  });
  const { errors, isSubmitting } = form.formState;
  const amount = form.watch("amount");
  const proof = form.watch("proof");
  const partial = typeof amount === "number" && amount > 0 && amount < invoice.remaining;

  async function onSubmit(values: FormValues) {
    try {
      const res = await create.mutateAsync({ invoice_id: invoice.id, ...values, notes: values.notes || null });
      toast.success(res.message ?? "Pembayaran tersimpan.");
      onSuccess(res);
    } catch (err) {
      if (!applyServerErrors(err, form.setError, ["amount", "paid_at", "method", "notes", "proof"])) {
        toast.error(getErrorMessage(err));
      }
    }
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
      <Field
        label="Nominal dibayar"
        htmlFor="pay-amount"
        required
        error={errors.amount?.message}
        hint={partial ? `Bayar sebagian — sisa setelah ini ${formatRupiah(invoice.remaining - amount)}.` : `Sisa tagihan ${formatRupiah(invoice.remaining)}.`}
      >
        <Controller control={form.control} name="amount" render={({ field }) => (
          <CurrencyInput id="pay-amount" className="h-12 text-lg font-semibold" value={field.value} onChange={(v) => field.onChange(v ?? undefined)} onBlur={field.onBlur} />
        )} />
      </Field>

      <Field label="Metode" required error={errors.method?.message}>
        <Controller control={form.control} name="method" render={({ field }) => (
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
            {METHODS.map((m) => (
              <button
                key={m}
                type="button"
                onClick={() => field.onChange(m)}
                className={cn(
                  "rounded-md border px-3 py-2.5 text-sm font-medium transition-colors",
                  field.value === m ? "border-primary bg-primary text-primary-foreground" : "bg-background hover:bg-muted",
                )}
                aria-pressed={field.value === m}
              >
                {PAYMENT_METHOD_LABELS[m]}
              </button>
            ))}
          </div>
        )} />
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Tanggal bayar" htmlFor="pay-date" required error={errors.paid_at?.message}>
          <Input id="pay-date" type="date" max={today} {...form.register("paid_at")} />
        </Field>
        <Field label="Bukti (opsional)" error={errors.proof?.message}>
          <Controller control={form.control} name="proof" render={({ field }) => (
            <>
              <input
                ref={fileRef}
                type="file"
                accept="image/*"
                capture="environment"
                className="hidden"
                onChange={(e) => field.onChange(e.target.files?.[0] ?? null)}
              />
              {proof ? (
                <div className="flex h-10 items-center justify-between gap-1 rounded-md border px-2 text-xs">
                  <span className="truncate">{proof.name}</span>
                  <button type="button" onClick={() => { field.onChange(null); if (fileRef.current) fileRef.current.value = ""; }} aria-label="Hapus foto">
                    <X className="h-4 w-4" />
                  </button>
                </div>
              ) : (
                <Button type="button" variant="outline" className="w-full" onClick={() => fileRef.current?.click()}>
                  <Camera /> Foto
                </Button>
              )}
            </>
          )} />
        </Field>
      </div>

      <Field label="Catatan" htmlFor="pay-notes" error={errors.notes?.message}>
        <Input id="pay-notes" placeholder="Opsional" {...form.register("notes")} />
      </Field>

      <Button type="submit" size="lg" className="w-full" disabled={isSubmitting}>
        {isSubmitting && <Loader2 className="animate-spin" />}
        {submitLabel}
      </Button>
    </form>
  );
}
