"use client";

import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDateTime } from "@/shared/lib/format-date";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/presentation/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import { Textarea } from "@/presentation/components/ui/textarea";
import { Button } from "@/presentation/components/ui/button";
import {
  ANTAI_EXCEPTION_STATUS_VALUES,
  ANTAI_EXCEPTION_TYPE_VALUES,
  ANTAI_EXCEPTION_RESOLUTION_VALUES,
} from "@/shared/constants/antai";
import {
  antaiExceptionSchema,
  type AntaiExceptionFormValues,
} from "@/shared/schemas/antai-exception.schema";
import type { AntaiVehicle, AntaiVehicleDetail } from "@/domain/entities/antai-vehicle";

const NONE = "__none__";

interface ExceptionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vehicle: AntaiVehicle | AntaiVehicleDetail | null;
  loading: boolean;
  onSubmit: (values: AntaiExceptionFormValues) => void;
}

export function ExceptionDialog({
  open,
  onOpenChange,
  vehicle,
  loading,
  onSubmit,
}: ExceptionDialogProps) {
  const t = useT();
  const locale = useLocale();
  const schema = useMemo(() => antaiExceptionSchema(t), [t]);

  const form = useForm<AntaiExceptionFormValues>({
    resolver: zodResolver(schema),
    defaultValues: { status: "open", exception_type: undefined, resolution: undefined, detail: "" },
  });

  const exception = vehicle?.exception ?? null;

  // Reseed the form from the vehicle's current exception each time the dialog opens.
  useEffect(() => {
    if (!open) return;
    const status = ANTAI_EXCEPTION_STATUS_VALUES.includes(
      exception?.status as (typeof ANTAI_EXCEPTION_STATUS_VALUES)[number]
    )
      ? (exception!.status as AntaiExceptionFormValues["status"])
      : "open";
    const type = ANTAI_EXCEPTION_TYPE_VALUES.includes(
      exception?.type as (typeof ANTAI_EXCEPTION_TYPE_VALUES)[number]
    )
      ? (exception!.type as AntaiExceptionFormValues["exception_type"])
      : undefined;
    const resolution = ANTAI_EXCEPTION_RESOLUTION_VALUES.includes(
      exception?.resolution as (typeof ANTAI_EXCEPTION_RESOLUTION_VALUES)[number]
    )
      ? (exception!.resolution as AntaiExceptionFormValues["resolution"])
      : undefined;
    form.reset({ status, exception_type: type, resolution, detail: exception?.detail ?? "" });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, vehicle?.id]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent onOpenAutoFocus={(e) => e.preventDefault()}>
        <DialogHeader>
          <DialogTitle>{t.antai.exception.title}</DialogTitle>
          <DialogDescription>{t.antai.exception.subtitle}</DialogDescription>
        </DialogHeader>

        {exception?.resolved_at && (
          <p className="text-xs text-muted-foreground -mt-2">
            {t.antai.exception.resolvedAt(formatDateTime(exception.resolved_at, locale))}
          </p>
        )}

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit((values) => onSubmit(values))}
            className="space-y-4"
          >
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t.antai.exception.statusLabel}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {ANTAI_EXCEPTION_STATUS_VALUES.map((v) => (
                        <SelectItem key={v} value={v}>
                          {t.antai.enums.exceptionStatus[v]}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="exception_type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t.antai.exception.typeLabel}</FormLabel>
                  <Select
                    value={field.value ?? NONE}
                    onValueChange={(v) => field.onChange(v === NONE ? undefined : v)}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value={NONE}>{t.antai.exception.none}</SelectItem>
                      {ANTAI_EXCEPTION_TYPE_VALUES.map((v) => (
                        <SelectItem key={v} value={v}>
                          {t.antai.enums.exceptionType[v]}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="resolution"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t.antai.exception.resolutionLabel}</FormLabel>
                  <Select
                    value={field.value ?? NONE}
                    onValueChange={(v) => field.onChange(v === NONE ? undefined : v)}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value={NONE}>{t.antai.exception.none}</SelectItem>
                      {ANTAI_EXCEPTION_RESOLUTION_VALUES.map((v) => (
                        <SelectItem key={v} value={v}>
                          {t.antai.enums.exceptionResolution[v]}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-[11px] text-muted-foreground">
                    {t.antai.exception.resolutionHelp}
                  </p>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="detail"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t.antai.exception.detailLabel}</FormLabel>
                  <FormControl>
                    <Textarea
                      rows={3}
                      placeholder={t.antai.exception.detailPlaceholder}
                      {...field}
                      value={field.value ?? ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex justify-end gap-2 pt-1">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                {t.common.cancel}
              </Button>
              <Button type="submit" disabled={loading}>
                {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                {t.antai.exception.submit}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
