'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Plus,
  Cpu,
  MapPin,
  Camera,
  Calendar,
  ClipboardList,
  AlertTriangle,
  ChevronRight,
} from 'lucide-react';
import {
  WizardHeader,
  PageLoader,
  InstallationStatusBadge,
  STATUS_STYLES,
} from '@/components/teltoinstall/_index';
import { useInstallationHistory } from '@/hooks/teltoinstall/_index';
import { resetInstallation } from '@/store/slices/installation-slice';
import { InstallationSummary } from '@/models/teltoinstall/_index';
import InstallationDetailModal from './InstallationDetailModal';

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 InstallationCard({
  installation,
  onClick,
}: {
  installation: InstallationSummary;
  onClick: () => void;
}) {
  const { t } = useTranslation();
  const style = STATUS_STYLES[installation.status] ?? STATUS_STYLES.in_progress;

  const plate = installation.vehicle?.license_plate || t('history.noPlate');
  const vin = installation.vehicle?.vin;
  const deviceLabel =
    installation.device?.model ||
    installation.device?.product_line ||
    t('history.deviceUnknown');
  const imei = installation.device?.imei;
  const date = installation.intervention_date || installation.created_at;
  const photos = installation.photos_count ?? 0;

  return (
    <button
      type="button"
      onClick={onClick}
      className={`w-full text-left bg-white rounded-xl shadow-sm border border-border border-l-4 ${style.border} overflow-hidden animate-slide-in active:scale-[0.99] transition-transform`}
    >
      <div className="p-4">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <p className="text-base font-bold text-foreground font-mono truncate">{plate}</p>
            {vin && <p className="text-xs text-muted-foreground mt-0.5 font-mono">{vin}</p>}
          </div>
          <div className="flex items-center gap-1.5 shrink-0">
            <InstallationStatusBadge status={installation.status} />
            <ChevronRight className="w-4 h-4 text-muted-foreground" />
          </div>
        </div>

        <div className="mt-3 flex items-center gap-2 text-sm text-foreground">
          <Cpu className="w-4 h-4 text-primary shrink-0" />
          <span className="font-medium">{deviceLabel}</span>
          {imei && <span className="font-mono text-xs text-muted-foreground truncate">· {imei}</span>}
        </div>

        <div className="mt-3 pt-3 border-t border-border grid grid-cols-1 gap-2 text-xs text-muted-foreground">
          <div className="flex items-center gap-1.5">
            <Calendar className="w-3.5 h-3.5 shrink-0" />
            <span>{formatDate(date)}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <MapPin className="w-3.5 h-3.5 shrink-0" />
            <span className="truncate">{installation.location || t('history.noLocation')}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <Camera className="w-3.5 h-3.5 shrink-0" />
            <span>{t('history.photos', { count: photos })}</span>
          </div>
        </div>
      </div>
    </button>
  );
}

export default function InstallationHistoryView() {
  const { t } = useTranslation();
  const router = useRouter();
  const dispatch = useDispatch();
  const { installations, loading, error } = useInstallationHistory();
  const [selectedId, setSelectedId] = useState<number | null>(null);

  const startNew = () => {
    dispatch(resetInstallation());
    router.push('/installation');
  };

  return (
    <div className="h-screen flex flex-col bg-background">
      <div className="flex-shrink-0">
        <WizardHeader />
      </div>

      <div className="flex-1 overflow-y-auto">
        <div className="w-full px-4 pt-4 pb-2">
          <h2 className="text-lg font-bold text-foreground leading-tight">{t('history.title')}</h2>
          <p className="text-sm text-muted-foreground">
            {t('history.subtitle', { count: installations.length })}
          </p>
        </div>

        <div className="w-full px-4 pb-28">
          {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>
          ) : installations.length === 0 ? (
            <div className="flex flex-col items-center justify-center text-center py-16 px-6">
              <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">
                <ClipboardList className="w-8 h-8 text-primary" />
              </div>
              <p className="text-base font-semibold text-foreground">{t('history.empty')}</p>
              <p className="text-sm text-muted-foreground mt-1 max-w-xs">{t('history.emptyHint')}</p>
              <button
                type="button"
                onClick={startNew}
                className="btn-primary mt-6 max-w-xs flex items-center justify-center gap-2"
              >
                <Plus className="w-4 h-4" />
                {t('history.newInstallation')}
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {installations.map((installation) => (
                <InstallationCard
                  key={installation.id}
                  installation={installation}
                  onClick={() => setSelectedId(installation.id)}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {!loading && installations.length > 0 && (
        <div className="flex-shrink-0 bg-white border-t border-border px-4 py-3 shadow-lg z-20">
          <div className="max-w-lg mx-auto">
            <button
              type="button"
              onClick={startNew}
              className="btn-primary flex items-center justify-center gap-2"
            >
              <Plus className="w-4 h-4" />
              {t('history.newInstallation')}
            </button>
          </div>
        </div>
      )}

      <InstallationDetailModal installationId={selectedId} onClose={() => setSelectedId(null)} />
    </div>
  );
}
