"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Car,
  Cpu,
  Cable,
  Satellite,
  Camera,
  FileText,
  Wrench,
  Loader2,
  AlertTriangle,
  Pencil,
  CheckCircle2,
  Link2,
  Link2Off,
  Plus,
} from "lucide-react";
import type { AxiosError } from "axios";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate, formatDateTime } from "@/shared/lib/format-date";
import { ROUTES } from "@/shared/constants";
import { StatusPill } from "@/presentation/components/telematics/status-pill";
import { Button } from "@/presentation/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import type { InstallationDetail } from "@/domain/entities/installation";

const PHOTO_TYPES = [
  "vin",
  "before_install",
  "after_install",
  "device_position",
  "incident",
];

interface Props {
  installationId: number | null;
  onClose: () => void;
  /** Notifié après une validation réussie (refresh liste). */
  onChanged?: () => void;
}

function Section({
  icon: Icon,
  title,
  children,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div className="border border-border rounded-xl overflow-hidden">
      <div className="flex items-center gap-2 px-4 py-2.5 bg-muted/50 border-b border-border">
        <Icon className="w-4 h-4 text-primary" />
        <span className="text-sm font-semibold text-foreground">{title}</span>
      </div>
      <div className="divide-y divide-border">{children}</div>
    </div>
  );
}

function DetailRow({
  label,
  value,
  mono = false,
}: {
  label: string;
  value?: string | number | null;
  mono?: boolean;
}) {
  return (
    <div className="flex items-center justify-between gap-4 px-4 py-2">
      <span className="text-xs text-muted-foreground">{label}</span>
      <span
        className={`text-sm text-foreground text-right ${mono ? "font-mono" : ""}`}
      >
        {value !== null && value !== undefined && value !== "" ? value : "—"}
      </span>
    </div>
  );
}

function ModalBody({ installation }: { installation: InstallationDetail }) {
  const t = useT();
  const locale = useLocale();
  const d = t.installations.detail;
  const vehicle = installation.vehicle;
  const device = installation.device;
  const validation = installation.validation;
  const wirings = installation.wirings.filter((w) => w.accessory);

  return (
    <div className="space-y-4">
      <Section icon={Wrench} title={d.sections.intervention}>
        <DetailRow label={d.fields.installer} value={installation.installer_name} />
        <DetailRow
          label={d.fields.interventionDate}
          value={
            installation.intervention_date
              ? formatDate(installation.intervention_date, locale)
              : null
          }
        />
        <DetailRow label={d.fields.location} value={installation.location} />
        <DetailRow
          label={d.fields.duration}
          value={
            installation.duration_minutes !== null
              ? t.installations.card.minutes(installation.duration_minutes)
              : null
          }
        />
      </Section>

      {vehicle && (
        <Section icon={Car} title={d.sections.vehicle}>
          <DetailRow label={d.fields.licensePlate} value={vehicle.license_plate} mono />
          <DetailRow label={d.fields.vin} value={vehicle.vin} mono />
          <div className="flex items-center justify-between gap-4 px-4 py-2">
            <span className="text-xs text-muted-foreground">
              {d.fields.fleetVehicle}
            </span>
            {vehicle.fleet_vehicle_id ? (
              <span className="inline-flex items-center gap-1.5 text-sm text-emerald-700">
                <Link2 className="w-3.5 h-3.5" />
                {d.fields.fleetLinked(vehicle.fleet_vehicle_id)}
              </span>
            ) : (
              <span className="inline-flex items-center gap-1.5 text-sm text-amber-600">
                <Link2Off className="w-3.5 h-3.5" />
                {d.fields.fleetNotLinked}
              </span>
            )}
          </div>
          <DetailRow
            label={d.fields.odometer}
            value={vehicle.odometer_km !== null ? `${vehicle.odometer_km} km` : null}
          />
          <DetailRow label={d.fields.hourMeter} value={vehicle.hour_meter} />
          <DetailRow
            label={d.fields.fuelLevel}
            value={vehicle.fuel_level ? d.fuelLevels[vehicle.fuel_level] ?? vehicle.fuel_level : null}
          />
        </Section>
      )}

      {device && (
        <Section icon={Cpu} title={d.sections.device}>
          <DetailRow label={d.fields.productLine} value={device.product_line} />
          <DetailRow label={d.fields.model} value={device.model} />
          <DetailRow label={d.fields.imei} value={device.imei} mono />
          <DetailRow
            label={d.fields.stockOrigin}
            value={
              device.stock_origin
                ? d.stockOrigins[device.stock_origin] ?? device.stock_origin
                : null
            }
          />
          <DetailRow
            label={d.fields.canModule}
            value={
              device.has_can_module
                ? device.can_module_type ?? t.common.yes
                : t.common.no
            }
          />
          <DetailRow label={d.fields.simIccid} value={device.sim_iccid} mono />
          <DetailRow label={d.fields.simOperator} value={device.sim_operator} />
        </Section>
      )}

      {installation.accessories.length > 0 && (
        <Section icon={Plus} title={d.sections.accessories}>
          <div className="px-4 py-2 flex flex-wrap gap-1.5">
            {installation.accessories.map((accessory) => (
              <span
                key={accessory.id}
                className="text-xs px-2 py-1 rounded-full bg-primary/10 text-primary"
              >
                {accessory.label}
              </span>
            ))}
          </div>
        </Section>
      )}

      {wirings.length > 0 && (
        <Section icon={Cable} title={d.sections.wiring}>
          {wirings.map((wiring) => (
            <div
              key={wiring.id}
              className="flex items-center justify-between gap-4 px-4 py-2"
            >
              <span className="inline-flex items-center gap-2 text-xs text-muted-foreground">
                {wiring.wire_color && (
                  <span
                    className="w-2.5 h-2.5 rounded-full border border-border"
                    style={{ backgroundColor: wiring.wire_color }}
                  />
                )}
                {wiring.wire ?? "—"}
              </span>
              <span className="text-sm text-foreground">{wiring.accessory}</span>
            </div>
          ))}
        </Section>
      )}

      {validation && (
        <Section icon={Satellite} title={d.sections.validation}>
          <DetailRow
            label={d.fields.contactDetected}
            value={
              validation.contact_detected === null
                ? null
                : validation.contact_detected
                  ? t.common.yes
                  : t.common.no
            }
          />
          <DetailRow
            label={d.fields.gpsDate}
            value={
              validation.gps_position_date
                ? formatDateTime(validation.gps_position_date, locale)
                : null
            }
          />
          <DetailRow label={d.fields.gpsAddress} value={validation.gps_address} />
          <DetailRow label={d.fields.satellites} value={validation.satellite_count} />
          <DetailRow
            label={d.fields.odometerGps}
            value={validation.odometer_km !== null ? `${validation.odometer_km} km` : null}
          />
          <DetailRow label={d.fields.hourMeterGps} value={validation.hour_meter} />
          <DetailRow
            label={d.fields.fuelLevelGps}
            value={
              validation.fuel_level
                ? d.fuelLevels[validation.fuel_level] ?? validation.fuel_level
                : null
            }
          />
        </Section>
      )}

      {installation.photos.length > 0 && (
        <Section icon={Camera} title={d.sections.photos}>
          <div className="p-4 space-y-4">
            {PHOTO_TYPES.map((type) => {
              const group = installation.photos.filter((p) => p.type === type);
              if (group.length === 0) return null;
              return (
                <div key={type}>
                  <p className="text-xs font-medium text-muted-foreground mb-2">
                    {d.photoTypes[type] ?? type}
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {group.map((photo) => (
                      <a
                        key={photo.id}
                        href={photo.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="block"
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={photo.url}
                          alt={photo.filename ?? d.photoTypes[type] ?? type}
                          className="w-20 h-20 object-cover rounded-lg border border-border"
                        />
                      </a>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </Section>
      )}

      {installation.notes && (
        <Section icon={FileText} title={d.sections.notes}>
          <p className="px-4 py-3 text-sm text-foreground whitespace-pre-wrap">
            {installation.notes}
          </p>
        </Section>
      )}
    </div>
  );
}

/** Extrait les messages d'une réponse 422 (complétude de validation). */
function extractErrors(err: unknown): string[] {
  const axiosError = err as AxiosError<{
    message?: string;
    errors?: string[] | Record<string, string[]>;
  }>;
  const data = axiosError.response?.data;
  if (!data) return [];
  if (Array.isArray(data.errors)) return data.errors;
  if (data.errors && typeof data.errors === "object") {
    return Object.values(data.errors).flat();
  }
  return data.message ? [data.message] : [];
}

export function InstallationDetailModal({ installationId, onClose, onChanged }: Props) {
  const t = useT();
  const locale = useLocale();
  const d = t.installations.detail;
  const router = useRouter();
  const container = useRepositories();

  const [validating, setValidating] = useState(false);
  const [actionErrors, setActionErrors] = useState<string[]>([]);

  const { data: installation, loading, error, refetch } = useApiQuery(
    () => container.installationRepository.findById(installationId as number),
    { enabled: installationId !== null, deps: [installationId] }
  );

  async function handleValidate() {
    if (installationId === null) return;
    setValidating(true);
    setActionErrors([]);
    try {
      await container.installationRepository.validate(installationId);
      await refetch();
      onChanged?.();
    } catch (err) {
      const messages = extractErrors(err);
      setActionErrors(messages.length > 0 ? messages : [d.actions.actionError]);
    } finally {
      setValidating(false);
    }
  }

  function handleClose() {
    setActionErrors([]);
    onClose();
  }

  return (
    <Dialog open={installationId !== null} onOpenChange={(open) => !open && handleClose()}>
      <DialogContent className="sm:max-w-2xl max-h-[88vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3">
            <span className="font-mono">
              {installation?.vehicle?.license_plate ?? t.installations.card.noPlate}
            </span>
            {installation && (
              <StatusPill
                label={installation.status_label}
                color={installation.status_color}
              />
            )}
          </DialogTitle>
          {installation && (
            <p className="text-xs text-muted-foreground">
              {formatDate(
                installation.intervention_date ?? installation.created_at,
                locale
              )}
            </p>
          )}
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
          </div>
        ) : error ? (
          <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg">
            <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
            <p className="text-sm text-red-600">{d.notFound}</p>
          </div>
        ) : installation ? (
          <>
            {actionErrors.length > 0 && (
              <div className="flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                <AlertTriangle className="w-4 h-4 text-red-600 shrink-0 mt-0.5" />
                <div className="text-sm text-red-600">
                  <p className="font-medium">{d.actions.incomplete}</p>
                  <ul className="mt-0.5 space-y-0.5 list-disc list-inside">
                    {actionErrors.map((message) => (
                      <li key={message}>{message}</li>
                    ))}
                  </ul>
                </div>
              </div>
            )}

            <ModalBody installation={installation} />

            <DialogFooter className="gap-2 sm:gap-2">
              <Button
                variant="outline"
                onClick={() => router.push(`${ROUTES.installations}/${installation.id}/edit`)}
              >
                <Pencil className="w-4 h-4 mr-2" />
                {d.actions.edit}
              </Button>
              {installation.status !== "validated" && (
                <Button onClick={handleValidate} disabled={validating}>
                  {validating ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      {d.actions.validating}
                    </>
                  ) : (
                    <>
                      <CheckCircle2 className="w-4 h-4 mr-2" />
                      {d.actions.validate}
                    </>
                  )}
                </Button>
              )}
            </DialogFooter>
          </>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}
