"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  ArrowLeft,
  Eye,
  EyeOff,
  Wrench,
  Loader2,
  Building2,
  AlertTriangle,
  ShieldOff,
} from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDateTime } from "@/shared/lib/format-date";
import { Button } from "@/presentation/components/ui/button";
import { Card, CardContent } from "@/presentation/components/ui/card";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { AntaiBadge } from "@/presentation/components/antai/antai-badges";
import { ExceptionDialog } from "@/presentation/components/antai/exception-dialog";
import { ANTAI_DISABLE_REASON_VALUES } from "@/shared/constants/antai";
import type { AntaiDisableReason } from "@/domain/entities/antai-vehicle";

function normVisibility(value?: string | null): "visible" | "hidden" | "exception" | "unknown" {
  const s = (value ?? "").toLowerCase();
  if (s === "visible" || s === "s") return "visible";
  if (s === "hidden" || s === "n") return "hidden";
  if (s === "exception" || s === "e") return "exception";
  return "unknown";
}

export default function AntaiVehicleDetailPage() {
  const t = useT();
  const locale = useLocale();
  usePageHeader(t.pages.antaiVehicleDetail.title, t.pages.antaiVehicleDetail.subtitle);
  const params = useParams();
  const router = useRouter();
  const repo = useRepositories().antaiVehicleRepository;
  const vehicleId = Number(params.id);

  const { data: vehicle, loading, refetch } = useApiQuery(
    () => repo.findById(vehicleId),
    { deps: [vehicleId], enabled: !!vehicleId }
  );

  const [enableOpen, setEnableOpen] = useState(false);
  const [disableOpen, setDisableOpen] = useState(false);
  const [disableReason, setDisableReason] = useState<AntaiDisableReason>("manual");
  const [exceptionOpen, setExceptionOpen] = useState(false);
  const [cascadeOpen, setCascadeOpen] = useState(false);

  const enableMutation = useApiMutation((id: number) => repo.enable(id), {
    successMessage: t.antai.toasts.enabled,
    onSuccess: () => {
      setEnableOpen(false);
      refetch();
    },
    onError: () => {
      setEnableOpen(false);
      refetch();
    },
  });

  const disableMutation = useApiMutation(
    ({ id, reason }: { id: number; reason: AntaiDisableReason }) =>
      repo.disable(id, reason),
    {
      successMessage: t.antai.toasts.disabled,
      onSuccess: () => {
        setDisableOpen(false);
        refetch();
      },
      onError: () => {
        setDisableOpen(false);
        refetch();
      },
    }
  );

  const exceptionMutation = useApiMutation(
    ({ id, payload }: { id: number; payload: Parameters<typeof repo.updateException>[1] }) =>
      repo.updateException(id, payload),
    {
      successMessage: t.antai.exception.updated,
      onSuccess: () => {
        setExceptionOpen(false);
        refetch();
      },
    }
  );

  const cascadeMutation = useApiMutation(
    (companyId: number) => repo.disableCompanyVehicles(companyId),
    {
      onSuccess: (res) => {
        toast.success(t.antai.cascade.queued(res?.queued ?? 0));
        setCascadeOpen(false);
        refetch();
      },
    }
  );

  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-12 w-72" />
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-4">
            <Skeleton className="h-48 rounded-xl" />
            <Skeleton className="h-48 rounded-xl" />
          </div>
          <Skeleton className="h-64 rounded-xl" />
        </div>
      </div>
    );
  }

  if (!vehicle) {
    return (
      <div className="p-6">
        <div className="flex items-center justify-center h-48 rounded-xl border border-dashed border-border">
          <p className="text-sm text-muted-foreground">{t.antai.detail.notFound}</p>
        </div>
      </div>
    );
  }

  const state = normVisibility(vehicle.antai_visibility?.value);
  const exception = vehicle.exception;
  const f = t.antai.detail.fields;

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-start gap-3">
        <Button variant="ghost" size="icon" onClick={() => router.push("/antai")}>
          <ArrowLeft className="w-4 h-4" />
        </Button>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-3 flex-wrap">
            <h2 className="text-xl font-bold text-foreground">
              {vehicle.vehicle_name || "—"}
            </h2>
            <AntaiBadge
              label={vehicle.antai_visibility?.label}
              color={vehicle.antai_visibility?.color}
            />
          </div>
          <p className="text-sm text-muted-foreground mt-0.5 font-mono">
            {vehicle.numberplate ?? "—"}
          </p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {state !== "visible" && (
            <Button
              size="sm"
              variant="outline"
              className="gap-1.5 text-emerald-600"
              onClick={() => setEnableOpen(true)}
            >
              <Eye className="w-4 h-4" />
              {t.antai.actions.enable}
            </Button>
          )}
          {state !== "hidden" && (
            <Button
              size="sm"
              variant="outline"
              className="gap-1.5 text-amber-600"
              onClick={() => {
                setDisableReason("manual");
                setDisableOpen(true);
              }}
            >
              <EyeOff className="w-4 h-4" />
              {t.antai.actions.disable}
            </Button>
          )}
          {exception && (
            <Button size="sm" variant="outline" className="gap-1.5" onClick={() => setExceptionOpen(true)}>
              <Wrench className="w-4 h-4" />
              {t.antai.actions.manageException}
            </Button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main */}
        <div className="lg:col-span-2 space-y-4">
          {/* ANTAI state */}
          <Card>
            <CardContent className="p-5 space-y-3">
              <h3 className="text-base font-semibold">{t.antai.detail.sections.antaiStatus}</h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                <BadgeRow label={f.visibility} badgeLabel={vehicle.antai_visibility?.label} color={vehicle.antai_visibility?.color} />
                <BadgeRow label={f.binding} badgeLabel={vehicle.binding_status?.label} color={vehicle.binding_status?.color} />
                <BadgeRow
                  label={f.archive}
                  badgeLabel={vehicle.archive_status?.archived ? vehicle.archive_status.label : undefined}
                  color={vehicle.archive_status?.color}
                />
                <TextRow label={f.unbindingReason} value={vehicle.unbinding_reason?.label} />
                <TextRow label={f.clientCode} value={vehicle.antai_client_code} mono />
                <TextRow
                  label={f.lastUpdate}
                  value={
                    vehicle.last_antai_updated_date
                      ? formatDateTime(vehicle.last_antai_updated_date, locale)
                      : undefined
                  }
                />
              </div>
            </CardContent>
          </Card>

          {/* Vehicle */}
          <Card>
            <CardContent className="p-5 space-y-3">
              <h3 className="text-base font-semibold">{t.antai.detail.sections.vehicle}</h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                <TextRow label={f.plate} value={vehicle.numberplate} mono />
                <TextRow label={f.vin} value={vehicle.vin} mono />
                <TextRow label={f.mark} value={vehicle.mark} />
                <TextRow label={f.model} value={vehicle.model} />
                <TextRow label={f.motorType} value={vehicle.motor_type} />
                <BadgeRow label={f.vehicleStatus} badgeLabel={vehicle.vehicle_status?.label} color={vehicle.vehicle_status?.color} />
                <TextRow
                  label={f.createdAt}
                  value={vehicle.created_at ? formatDateTime(vehicle.created_at, locale) : undefined}
                />
              </div>
            </CardContent>
          </Card>

          {/* Exception */}
          {exception && (
            <Card className="border-l-4 border-l-red-500">
              <CardContent className="p-5 space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <h3 className="text-base font-semibold flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4 text-red-500" />
                    {t.antai.detail.sections.exception}
                  </h3>
                  <Button size="sm" variant="outline" className="gap-1.5" onClick={() => setExceptionOpen(true)}>
                    <Wrench className="w-4 h-4" />
                    {t.antai.actions.manageException}
                  </Button>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                  <TextRow label={f.exceptionType} value={exception.type_label} />
                  <BadgeRow label={f.exceptionStatus} badgeLabel={exception.status_label} color={exception.status_color} />
                  <TextRow label={f.exceptionResolution} value={exception.resolution_label} />
                  <TextRow
                    label={f.resolvedAt}
                    value={exception.resolved_at ? formatDateTime(exception.resolved_at, locale) : undefined}
                  />
                </div>
                {exception.detail && (
                  <div className="pt-1">
                    <p className="text-xs font-medium text-muted-foreground mb-1">{f.exceptionDetail}</p>
                    <p className="text-sm rounded-lg bg-muted/50 p-3 whitespace-pre-wrap">{exception.detail}</p>
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          <Card>
            <CardContent className="p-5 space-y-3">
              <h3 className="text-base font-semibold flex items-center gap-2">
                <Building2 className="w-4 h-4 text-muted-foreground" />
                {t.antai.detail.sections.company}
              </h3>
              <div className="space-y-2">
                <p className="text-sm font-medium">{vehicle.company?.name ?? "—"}</p>
                <AntaiBadge
                  label={vehicle.company_account_status?.label}
                  color={vehicle.company_account_status?.color}
                />
              </div>
              {vehicle.company && (
                <div className="pt-2 border-t border-border">
                  <Button
                    variant="outline"
                    size="sm"
                    className="w-full gap-1.5 text-amber-600"
                    onClick={() => setCascadeOpen(true)}
                  >
                    <ShieldOff className="w-4 h-4" />
                    {t.antai.cascade.action}
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Enable */}
      <ConfirmationDialog
        open={enableOpen}
        onOpenChange={setEnableOpen}
        title={t.antai.enable.title}
        description={t.antai.enable.description(vehicle.vehicle_name || "")}
        confirmLabel={t.common.confirm}
        loading={enableMutation.loading}
        onConfirm={() => enableMutation.mutate(vehicle.id)}
      />

      {/* Disable */}
      <Dialog open={disableOpen} onOpenChange={setDisableOpen}>
        <DialogContent onOpenAutoFocus={(e) => e.preventDefault()}>
          <DialogHeader>
            <DialogTitle>{t.antai.disable.title}</DialogTitle>
            <DialogDescription>
              {t.antai.disable.description(vehicle.vehicle_name || "")}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-1.5">
            <label className="text-xs font-medium text-muted-foreground">
              {t.antai.disable.reasonLabel}
            </label>
            <Select value={disableReason} onValueChange={(v) => setDisableReason(v as AntaiDisableReason)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {ANTAI_DISABLE_REASON_VALUES.map((v) => (
                  <SelectItem key={v} value={v}>
                    {t.antai.enums.disableReason[v]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDisableOpen(false)}>
              {t.common.cancel}
            </Button>
            <Button
              className="bg-amber-600 text-white hover:bg-amber-700"
              disabled={disableMutation.loading}
              onClick={() => disableMutation.mutate({ id: vehicle.id, reason: disableReason })}
            >
              {disableMutation.loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              {t.common.confirm}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Exception */}
      <ExceptionDialog
        open={exceptionOpen}
        onOpenChange={setExceptionOpen}
        vehicle={vehicle}
        loading={exceptionMutation.loading}
        onSubmit={(values) =>
          exceptionMutation.mutate({
            id: vehicle.id,
            payload: {
              ...values,
              detail: values.detail?.trim() ? values.detail.trim() : undefined,
            },
          })
        }
      />

      {/* Company cascade */}
      <ConfirmationDialog
        open={cascadeOpen}
        onOpenChange={setCascadeOpen}
        title={t.antai.cascade.title}
        description={t.antai.cascade.description(vehicle.company?.name ?? "")}
        confirmLabel={t.common.confirm}
        variant="destructive"
        loading={cascadeMutation.loading}
        onConfirm={() => vehicle.company && cascadeMutation.mutate(vehicle.company.id)}
      />
    </div>
  );
}

function TextRow({
  label,
  value,
  mono,
}: {
  label: string;
  value?: string | null;
  mono?: boolean;
}) {
  return (
    <div className="min-w-0">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <p className={`text-sm truncate ${mono ? "font-mono" : ""}`}>{value || "—"}</p>
    </div>
  );
}

function BadgeRow({
  label,
  badgeLabel,
  color,
}: {
  label: string;
  badgeLabel?: string | null;
  color?: string | null;
}) {
  return (
    <div className="min-w-0">
      <p className="text-xs font-medium text-muted-foreground mb-1">{label}</p>
      <AntaiBadge label={badgeLabel} color={color} />
    </div>
  );
}
