'use client';

import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
  X,
  Car,
  Cpu,
  Cable,
  MapPin,
  Satellite,
  Camera,
  FileText,
  AlertTriangle,
  Pencil,
} from 'lucide-react';
import { SectionCard, DetailItem, PageLoader, InstallationStatusBadge, WireBadge } from '@/components/teltoinstall/_index';
import { useInstallationDetail, useResumeInstallation } from '@/hooks/teltoinstall/_index';
import { InstallationDetail } from '@/models/teltoinstall/_index';

interface Props {
  installationId: number | null;
  onClose: () => void;
}

const PHOTO_TYPES = ['vin', 'before_install', 'after_install', 'odometer', 'device_position', 'incident'] as const;

function formatDate(value?: string | null): string {
  if (!value) return '—';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric' });
}

function VehicleSection({ installation }: { installation: InstallationDetail }) {
  const { t } = useTranslation();
  const v = installation.vehicle;
  return (
    <SectionCard icon={<Car className="w-4 h-4" />} title={t('wizard.steps.vehicle')} noPadding>
      <div className="divide-y divide-border">
        <DetailItem label={t('vehicle.licensePlate')} value={v?.license_plate} />
        <DetailItem label={t('vehicle.vin')} value={v?.vin} />
        <DetailItem label={t('vehicle.odometerKm')} value={v?.odometer_km != null ? `${v.odometer_km} km` : null} />
        <DetailItem label={t('vehicle.hourMeter')} value={v?.hour_meter != null ? `${v.hour_meter} min` : null} />
        <DetailItem
          label={t('vehicle.fuelLevel')}
          value={v?.fuel_level ? t(`validation.fuelLevels.${v.fuel_level}`) : null}
        />
      </div>
    </SectionCard>
  );
}

function DeviceSection({ installation }: { installation: InstallationDetail }) {
  const { t } = useTranslation();
  const d = installation.device;
  return (
    <SectionCard icon={<Cpu className="w-4 h-4" />} title={t('device.sectionTitle')} noPadding>
      <div className="divide-y divide-border">
        <DetailItem label={t('device.productLine')} value={d?.product_line} />
        <DetailItem label={t('device.model')} value={d?.model} />
        <DetailItem label={t('validation.imei')} value={d?.imei} />
        <DetailItem label={t('device.stockOrigin')} value={d?.stock_origin} />
        <DetailItem
          label={t('device.hasCanModule')}
          value={d?.has_can_module ? d?.can_module_type?.label ?? t('device.canModuleYes') : t('device.canModuleNo')}
        />
        <DetailItem label={t('device.iccid')} value={d?.sim_card?.iccid} />
      </div>
    </SectionCard>
  );
}

function WiringSection({ installation }: { installation: InstallationDetail }) {
  const { t } = useTranslation();
  const wirings = (installation.wirings ?? []).filter((w) => w.wire_accessory);
  if (!installation.location && wirings.length === 0) return null;

  return (
    <SectionCard icon={<Cable className="w-4 h-4" />} title={t('wiring.sectionWires')} noPadding>
      <div className="p-4 pb-0">
        <DetailItem label={t('wiring.location')} value={installation.location} />
      </div>
      {wirings.length > 0 && (
        <table className="w-full">
          <thead>
            <tr className="border-b border-border bg-muted/50">
              <th className="px-4 py-2 text-left text-xs font-semibold text-muted-foreground w-[40%]">
                {t('wiring.colWire')}
              </th>
              <th className="px-4 py-2 text-left text-xs font-semibold text-muted-foreground">
                {t('wiring.colAccessory')}
              </th>
            </tr>
          </thead>
          <tbody>
            {wirings.map((w) => (
              <tr key={w.id} className="border-b border-border last:border-b-0">
                <td className="px-4 py-2.5">
                  <WireBadge label={w.wire?.label ?? '—'} color={w.wire?.color} />
                </td>
                <td className="px-4 py-2.5 text-sm text-foreground">{w.wire_accessory?.label}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </SectionCard>
  );
}

function ValidationSection({ installation }: { installation: InstallationDetail }) {
  const { t } = useTranslation();
  const val = installation.installation_validation;
  if (!val) return null;
  return (
    <SectionCard icon={<Satellite className="w-4 h-4" />} title={t('validation.sectionValidation')} noPadding>
      <div className="divide-y divide-border">
        <DetailItem
          label={t('validation.contactDetected')}
          value={val.contact_detected ? t('validation.testSuccess') : '—'}
        />
        <DetailItem label={t('validation.gpsPositionDate')} value={formatDate(val.gps_position_date)} />
        <DetailItem label={t('validation.gpsAddress')} value={val.gps_address} />
        <DetailItem
          label={t('validation.satelliteCount')}
          value={val.satellite_count != null ? `${val.satellite_count}` : null}
        />
        <DetailItem
          label={`${t('vehicle.odometerKm')} (GPS)`}
          value={val.odometer_km != null ? `${val.odometer_km} km` : null}
        />
        <DetailItem
          label={`${t('vehicle.hourMeter')} (GPS)`}
          value={val.hour_meter != null ? `${val.hour_meter}` : null}
        />
        <DetailItem
          label={`${t('vehicle.fuelLevel')} (GPS)`}
          value={val.fuel_level ? t(`validation.fuelLevels.${val.fuel_level}`) : null}
        />
      </div>
    </SectionCard>
  );
}

function PhotosSection({ installation }: { installation: InstallationDetail }) {
  const { t } = useTranslation();
  const photos = installation.photos ?? [];
  if (photos.length === 0) return null;

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

export default function InstallationDetailModal({ installationId, onClose }: Props) {
  const { t } = useTranslation();
  const { installation, loading, error } = useInstallationDetail(installationId);
  const { resume } = useResumeInstallation();

  useEffect(() => {
    if (installationId == null) return;
    const original = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = original;
    };
  }, [installationId]);

  useEffect(() => {
    if (installationId == null) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [installationId, onClose]);

  if (installationId == null) return null;

  const title = installation?.vehicle?.license_plate || t('history.noPlate');

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
      <div className="absolute inset-0 bg-black/50 animate-fade-in" onClick={onClose} />

      <div className="relative w-full bg-background rounded-t-2xl sm:rounded-2xl shadow-2xl max-h-[92vh] sm:max-h-[88vh] flex flex-col overflow-hidden animate-slide-in">
        {/* Header */}
        <div
          className="flex-shrink-0 px-4 py-3 flex items-center justify-between gap-3"
          style={{ background: 'linear-gradient(135deg, #0A1628 0%, #067efb 100%)' }}
        >
          <div className="min-w-0">
            <p className="text-white font-bold text-base font-mono truncate">{title}</p>
            {installation && (
              <p className="text-blue-200 text-xs">
                {formatDate(installation.intervention_date || installation.created_at)}
              </p>
            )}
          </div>
          <div className="flex items-center gap-2 shrink-0">
            {installation && <InstallationStatusBadge status={installation.status} />}
            <button
              type="button"
              onClick={onClose}
              aria-label={t('history.close')}
              className="w-8 h-8 rounded-full bg-white/15 hover:bg-white/25 flex items-center justify-center text-white transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4">
          {loading ? (
            <PageLoader />
          ) : 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">{t(error)}</p>
            </div>
          ) : installation ? (
            <>
              <VehicleSection installation={installation} />
              <DeviceSection installation={installation} />
              <WiringSection installation={installation} />
              <ValidationSection installation={installation} />
              <PhotosSection installation={installation} />
              {installation.notes && (
                <SectionCard icon={<FileText className="w-4 h-4" />} title={t('photos.sectionComments')}>
                  <p className="text-sm text-foreground whitespace-pre-wrap">{installation.notes}</p>
                </SectionCard>
              )}
              {installation.installer_name && (
                <div className="flex items-center gap-2 px-1 pb-2 text-xs text-muted-foreground">
                  <MapPin className="w-3.5 h-3.5" />
                  <span>{t('validation.installer')}: {installation.installer_name}</span>
                </div>
              )}
            </>
          ) : null}
        </div>

        {/* Footer — resume (in progress) or correct (GPS error); hidden once validated */}
        {installation && installation.status !== 'validated' && (
          <div className="flex-shrink-0 bg-white border-t border-border px-4 py-3 shadow-lg">
            <button
              type="button"
              onClick={() => resume(installation)}
              className="btn-primary flex items-center justify-center gap-2"
            >
              <Pencil className="w-4 h-4 shrink-0" />
              <span>{t('history.resumeOrCorrect')}</span>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
