import { useEffect, useState } from 'react'

export type Disciplinaire = {
  id: number
  num_salarie: number | null
  sanction: string | null
  datedu: string | null
  dateau: string | null
  commentaire: string | null
  libelle_date_buttoir: string | null
  date_buttoir: string | null
  arreter_alerte: boolean | null
  motif: string | null
  date_creation: string | null
}

export type TypeSanction = {
  id: number
  sanction: string | null
  nbjoursprevenir?: number | null
  significationdatebuttoir?: string | null
  intervalle?: string | null
}

export type DisciplinaireForm = {
  sanction: string
  datedu: string
  dateau: string
  commentaire: string
  libelle_date_buttoir: string
  date_buttoir: string
  arreter_alerte: boolean
  motif: string
}

type Props = {
  disciplinaire: Disciplinaire | null
  typesSanctions: TypeSanction[]
  saving: boolean
  onClose: () => void
  onDelete: () => void
  onSave: (form: DisciplinaireForm) => void
}

function formatDateForInput(value?: string | null) {
  if (!value) return ''
  return value.slice(0, 10)
}

function createForm(disciplinaire: Disciplinaire | null): DisciplinaireForm {
  return {
    sanction: disciplinaire?.sanction ?? '',
    datedu: formatDateForInput(disciplinaire?.datedu),
    dateau: formatDateForInput(disciplinaire?.dateau),
    commentaire: disciplinaire?.commentaire ?? '',
    libelle_date_buttoir: disciplinaire?.libelle_date_buttoir ?? '',
    date_buttoir: formatDateForInput(disciplinaire?.date_buttoir),
    arreter_alerte: disciplinaire?.arreter_alerte ?? false,
    motif: disciplinaire?.motif ?? '',
  }
}

export default function DisciplinairesPanel({
  disciplinaire,
  typesSanctions,
  saving,
  onClose,
  onDelete,
  onSave,
}: Props) {
  const [form, setForm] = useState(() => createForm(disciplinaire))

  useEffect(() => {
    setForm(createForm(disciplinaire))
  }, [disciplinaire])

  function selectTypeSanction(value: string) {
    const selectedType = typesSanctions.find(
      (type) => type.sanction === value,
    )

    setForm((previous) => ({
      ...previous,
      sanction: value,
      libelle_date_buttoir:
        selectedType?.significationdatebuttoir ??
        previous.libelle_date_buttoir,
    }))
  }

  return (
    <div className="mt-3 w-full max-w-[760px] border border-blue-300 bg-blue-50 p-3 shadow">
      <div className="mb-3 flex items-center justify-between">
        <h3 className="text-sm font-bold text-blue-700">
          {disciplinaire
            ? 'Modifier une sanction disciplinaire'
            : 'Ajouter une sanction disciplinaire'}
        </h3>

        <button type="button" onClick={onClose} className="text-xs text-black">
          ✕
        </button>
      </div>

      <div className="grid grid-cols-[180px_1fr] items-center gap-2 text-xs text-black">
        <label htmlFor="sanction">Sanction</label>
        <select
          id="sanction"
          value={form.sanction}
          onChange={(event) => selectTypeSanction(event.target.value)}
          className="h-7 w-full border border-slate-400 bg-white px-2"
        >
          <option value="">Sélectionner un type de sanction</option>

          {form.sanction &&
            !typesSanctions.some(
              (type) => type.sanction === form.sanction,
            ) && (
              <option value={form.sanction}>{form.sanction}</option>
            )}

          {typesSanctions
            .filter((type) => Boolean(type.sanction?.trim()))
            .map((type) => (
              <option key={type.id} value={type.sanction ?? ''}>
                {type.sanction}
              </option>
            ))}
        </select>

        <label htmlFor="libelle-date-buttoir">Libellé de la date butoir</label>
        <input
          id="libelle-date-buttoir"
          type="text"
          value={form.libelle_date_buttoir}
          onChange={(event) =>
            setForm((previous) => ({
              ...previous,
              libelle_date_buttoir: event.target.value,
            }))
          }
          className="h-7 border border-slate-400 bg-white px-2"
          placeholder="Ex. Date d'envoi du courrier"
        />

        <label htmlFor="date-buttoir">Date butoir</label>
        <input
          id="date-buttoir"
          type="date"
          value={form.date_buttoir}
          onChange={(event) =>
            setForm((previous) => ({
              ...previous,
              date_buttoir: event.target.value,
            }))
          }
          className="h-7 border border-slate-400 bg-white px-2"
        />

        <label htmlFor="date-du">Du</label>
        <input
          id="date-du"
          type="date"
          value={form.datedu}
          onChange={(event) =>
            setForm((previous) => ({ ...previous, datedu: event.target.value }))
          }
          className="h-7 border border-slate-400 bg-white px-2"
        />

        <label htmlFor="date-au">Au</label>
        <input
          id="date-au"
          type="date"
          min={form.datedu || undefined}
          value={form.dateau}
          onChange={(event) =>
            setForm((previous) => ({ ...previous, dateau: event.target.value }))
          }
          className="h-7 border border-slate-400 bg-white px-2"
        />

        <label htmlFor="arreter-alerte">Arrêter l'alerte</label>
        <input
          id="arreter-alerte"
          type="checkbox"
          checked={form.arreter_alerte}
          onChange={(event) =>
            setForm((previous) => ({
              ...previous,
              arreter_alerte: event.target.checked,
            }))
          }
          className="h-4 w-4"
        />

        <label htmlFor="motif">Motif</label>
        <textarea
          id="motif"
          value={form.motif}
          onChange={(event) =>
            setForm((previous) => ({ ...previous, motif: event.target.value }))
          }
          rows={3}
          className="resize-y border border-slate-400 bg-white px-2 py-1"
          placeholder="Ajouter un motif..."
        />

        <label htmlFor="commentaire" className="self-start pt-1">
          Commentaire
        </label>
        <textarea
          id="commentaire"
          value={form.commentaire}
          onChange={(event) =>
            setForm((previous) => ({
              ...previous,
              commentaire: event.target.value,
            }))
          }
          rows={3}
          className="resize-y border border-slate-400 bg-white px-2 py-1"
          placeholder="Ajouter un commentaire administratif..."
        />
      </div>

      <div className="mt-3 flex justify-between">
        <div>
          {disciplinaire && (
            <button
              type="button"
              onClick={onDelete}
              disabled={saving}
              className="border border-red-600 px-3 py-1 text-xs text-red-600 hover:bg-red-600 hover:text-white disabled:opacity-50"
            >
              Supprimer
            </button>
          )}
        </div>

        <div className="flex gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={saving}
            className="border border-slate-400 px-3 py-1 text-xs text-black disabled:opacity-50"
          >
            Annuler
          </button>

          <button
            type="button"
            disabled={saving}
            onClick={() => {
              if (!form.sanction.trim()) {
                alert('Veuillez renseigner une sanction.')
                return
              }

              if (form.datedu && form.dateau && form.dateau < form.datedu) {
                alert("La date de fin ne peut pas être antérieure à la date de début.")
                return
              }

              onSave(form)
            }}
            className="bg-blue-600 px-3 py-1 text-xs text-white hover:bg-blue-700 disabled:opacity-50"
          >
            {saving
              ? 'Enregistrement...'
              : disciplinaire
                ? 'Modifier'
                : 'Enregistrer'}
          </button>
        </div>
      </div>
    </div>
  )
}