'use client';

import React from 'react';
import { Formik, Form } from 'formik';
import { MapPin, Cable, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { FormTextField, SectionCard, WireBadge, FormikErrorToast } from '@/components/teltoinstall/_index';
import { useWiringStep, useReferenceData } from '@/hooks/teltoinstall/_index';
import { WIZARD_FORM_ID } from '../constants';

interface Props {
  onNext: () => void;
}

export default function WiringStep({ onNext }: Props) {
  const { t } = useTranslation();
  const { wirings, location, productLine, model, validationSchema, updateWiring, saveWiring } = useWiringStep();
  const { wires, wireAccessories, deviceModels } = useReferenceData();

  // N'afficher que les fils du modèle de boîtier choisi à l'étape 2 (brochage du modèle).
  // Repli : tous les fils si le modèle n'est pas répertorié (ex. gamme « other » en saisie libre).
  const selectedModel = deviceModels.find(
    (m) => m.label === model && m.product_line === productLine
  );
  const visibleWires = selectedModel?.wire_ids
    ? wires.filter((wire) => selectedModel.wire_ids!.includes(wire.id))
    : wires;

  return (
    <Formik
      initialValues={{ location: location ?? '' }}
      validationSchema={validationSchema}
      enableReinitialize
      onSubmit={async (values) => {
        const ok = await saveWiring(values.location);
        if (ok) onNext();
      }}
    >
      <Form id={WIZARD_FORM_ID}>
        <FormikErrorToast />
        <SectionCard icon={<MapPin className="w-4 h-4" />} title={t('wiring.sectionImplantation')}>
          <FormTextField
            name="location"
            label={t('wiring.location')}
            placeholder={t('wiring.locationPlaceholder')}
            required
          />
        </SectionCard>

        <SectionCard icon={<Cable className="w-4 h-4" />} title={t('wiring.sectionWires')}>
          {visibleWires.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-4">
              {t('wiring.noWiresForLine')}
            </p>
          ) : (
          <div className="overflow-x-auto -mx-4">
            <table className="w-full min-w-[300px]">
              <thead>
                <tr className="border-b border-border bg-muted/50">
                  <th className="px-3 py-2 text-left text-xs font-semibold text-muted-foreground w-[38%]">
                    {t('wiring.colWire')}
                  </th>
                  <th className="px-3 py-2 text-left text-xs font-semibold text-muted-foreground">
                    {t('wiring.colAccessory')}
                  </th>
                </tr>
              </thead>
              <tbody>
                {visibleWires.map((wire) => {
                  const selected = wirings.find((w) => w.wire_id === wire.id)?.wire_accessory_id;
                  return (
                    <tr key={wire.id} className="border-b border-border last:border-b-0">
                      <td className="px-3 py-2.5">
                        <WireBadge label={wire.label} color={wire.color} />
                      </td>
                      <td className="px-3 py-2.5">
                        <select
                          className="w-full text-sm border border-input rounded-lg px-2 py-2 bg-white focus:outline-none focus:ring-1 focus:ring-primary"
                          value={selected !== undefined ? String(selected) : ''}
                          onChange={(e) =>
                            updateWiring(wire.id, e.target.value ? Number(e.target.value) : undefined)
                          }
                        >
                          <option value="">{t('wiring.notConnected')}</option>
                          {wireAccessories.map((wa) => (
                            <option key={wa.id} value={String(wa.id)}>
                              {wa.label}
                            </option>
                          ))}
                        </select>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          )}

          <div className="flex items-start gap-2 p-3 bg-amber-50 rounded-lg border border-amber-200 mt-4">
            <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
            <p className="text-xs text-amber-700">{t('wiring.warning')}</p>
          </div>
        </SectionCard>
      </Form>
    </Formik>
  );
}
