import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import type {
    CrujiaConfig,
    CrujiaSeveridad,
    Inventario173ModificacionData,
} from '@/types/fichas-inventario';

interface ModificacionesAlteracionesProps {
    crujias: CrujiaConfig[];
    modificaciones: Inventario173ModificacionData[];
    onModificacionChange: (
        index: number,
        modificacion: Inventario173ModificacionData,
    ) => void;
}

const SEVERIDADES: Array<keyof CrujiaSeveridad> = ['l', 'm', 'a'];

function getColumnasVisibles(crujias: CrujiaConfig[]): {
    crujias: CrujiaConfig[];
    tieneOtros: boolean;
    otrosIds: number[];
} {
    if (crujias.length <= 3) {
        return { crujias, tieneOtros: false, otrosIds: [] };
    }

    return {
        crujias: crujias.slice(0, 3),
        tieneOtros: true,
        otrosIds: crujias.slice(3).map((c) => c.id),
    };
}

export function ModificacionesAlteraciones({
    crujias,
    modificaciones,
    onModificacionChange,
}: ModificacionesAlteracionesProps) {
    if (crujias.length === 0) {
        return (
            <div className="rounded-lg border border-border bg-muted/20 p-6 text-center">
                <p className="text-sm font-medium text-muted-foreground">
                    No hay crujías configuradas en la sección 16.1
                </p>
                <p className="mt-1 text-xs text-muted-foreground">
                    Primero debes configurar las crujías en la sección 16.1 para poder registrar modificaciones y alteraciones.
                </p>
            </div>
        );
    }

    const {
        crujias: crujiasVisibles,
        tieneOtros,
        otrosIds,
    } = getColumnasVisibles(crujias);

    const totalCols = crujiasVisibles.length + (tieneOtros ? 1 : 0);

    function setSeveridad(
        index: number,
        crujiaId: string | number,
        severidad: keyof CrujiaSeveridad,
        value: boolean,
    ) {
        const mod = modificaciones[index];
        if (!mod) {
            return;
        }

        const currentJson = mod.crujias_json ?? {};
        const currentCrujia = currentJson[String(crujiaId)] ?? {};

        onModificacionChange(index, {
            ...mod,
            crujias_json: {
                ...currentJson,
                [String(crujiaId)]: {
                    ...currentCrujia,
                    [severidad]: value,
                },
            },
        });
    }

    function isChecked(
        mod: Inventario173ModificacionData,
        crujiaId: string | number,
        severidad: keyof CrujiaSeveridad,
    ): boolean {
        return mod.crujias_json?.[String(crujiaId)]?.[severidad] ?? false;
    }

    return (
        <div className="overflow-x-auto rounded-lg border border-border">
            <table className="w-full border-collapse text-sm">
                <thead>
                    <tr className="bg-muted/40">
                        <th
                            rowSpan={2}
                            className="min-w-[180px] px-3 py-2 text-left text-xs font-semibold tracking-wide text-muted-foreground uppercase"
                        >
                            MODIFICACIONES Y/O ALTERACIONES
                        </th>
                        {crujiasVisibles.map((crujia) => (
                            <th
                                key={crujia.id}
                                colSpan={3}
                                className="border-l border-border px-2 py-1.5 text-center text-xs font-semibold tracking-wide text-muted-foreground uppercase"
                            >
                                {crujia.codigo}
                            </th>
                        ))}
                        {tieneOtros && (
                            <th
                                colSpan={3}
                                className="border-l border-border px-2 py-1.5 text-center text-xs font-semibold tracking-wide text-muted-foreground uppercase"
                            >
                                OTROS
                            </th>
                        )}
                    </tr>
                    <tr className="bg-muted/20 text-xs text-muted-foreground">
                        {Array.from({ length: totalCols }).map((_, colIndex) => (
                            <React.Fragment key={colIndex}>
                                <th
                                    key={`${colIndex}-l`}
                                    className="border-l border-border px-2 py-1 text-center"
                                >
                                    L
                                </th>
                                <th
                                    key={`${colIndex}-m`}
                                    className="px-2 py-1 text-center"
                                >
                                    M
                                </th>
                                <th
                                    key={`${colIndex}-a`}
                                    className="px-2 py-1 text-center"
                                >
                                    A
                                </th>
                            </React.Fragment>
                        ))}
                    </tr>
                </thead>
                <tbody className="divide-y divide-border/60">
                    {/* Grupo ALTER. */}
                    {modificaciones
                        .filter((m) => m.grupo === 'alteracion')
                        .map((mod, index) => {
                            const globalIndex = modificaciones.indexOf(mod);
                            const isFirst = index === 0;

                            return (
                                <tr
                                    key={`${mod.grupo}-${mod.codigo}`}
                                    className="align-middle transition-colors hover:bg-muted/30"
                                >
                                    <td className="px-3 py-2">
                                        {isFirst && (
                                            <span className="mr-2 text-[10px] font-bold text-muted-foreground">
                                                ALTER.
                                            </span>
                                        )}
                                        <span className="text-xs font-medium">
                                            {mod.nombre}
                                        </span>
                                    </td>
                                    {crujiasVisibles.map((crujia) =>
                                        SEVERIDADES.map((sev, sevIndex) => (
                                            <td
                                                key={`${mod.codigo}-${crujia.id}-${sev}`}
                                                className={`px-2 py-1.5 text-center ${
                                                    sevIndex === 0
                                                        ? 'border-l border-border/60'
                                                        : ''
                                                }`}
                                            >
                                                <Checkbox
                                                    checked={isChecked(
                                                        mod,
                                                        crujia.id,
                                                        sev,
                                                    )}
                                                    onCheckedChange={(
                                                        checked,
                                                    ) =>
                                                        setSeveridad(
                                                            globalIndex,
                                                            crujia.id,
                                                            sev,
                                                            Boolean(checked),
                                                        )
                                                    }
                                                />
                                            </td>
                                        )),
                                    )}
                                    {tieneOtros &&
                                        SEVERIDADES.map((sev, sevIndex) => (
                                            <td
                                                key={`${mod.codigo}-otros-${sev}`}
                                                className={`px-2 py-1.5 text-center ${
                                                    sevIndex === 0
                                                        ? 'border-l border-border/60'
                                                        : ''
                                                }`}
                                            >
                                                <Checkbox
                                                    checked={ otrosIds.some(
                                                            (id) =>
                                                                isChecked(
                                                                    mod,
                                                                    id,
                                                                    sev,
                                                                ),
                                                        )}
                                                    onCheckedChange={(
                                                        checked,
                                                    ) => {
                                                        for (const id of otrosIds) {
                                                            setSeveridad(
                                                                globalIndex,
                                                                id,
                                                                sev,
                                                                Boolean(
                                                                    checked,
                                                                ),
                                                            );
                                                        }
                                                    }}
                                                />
                                            </td>
                                        ))}
                                </tr>
                            );
                        })}
                    {/* Grupo ELEMENTOS */}
                    {modificaciones
                        .filter((m) => m.grupo === 'elemento')
                        .map((mod, index) => {
                            const globalIndex = modificaciones.indexOf(mod);
                            const isFirst = index === 0;

                            return (
                                <tr
                                    key={`${mod.grupo}-${mod.codigo}`}
                                    className="align-middle transition-colors hover:bg-muted/30"
                                >
                                    <td className="px-3 py-2">
                                        {isFirst && (
                                            <span className="mr-2 text-[10px] font-bold text-muted-foreground">
                                                ELEMENTOS
                                            </span>
                                        )}
                                        <span className="text-xs font-medium">
                                            {mod.nombre}
                                        </span>
                                    </td>
                                    {crujiasVisibles.map((crujia) =>
                                        SEVERIDADES.map((sev, sevIndex) => (
                                            <td
                                                key={`${mod.codigo}-${crujia.id}-${sev}`}
                                                className={`px-2 py-1.5 text-center ${
                                                    sevIndex === 0
                                                        ? 'border-l border-border/60'
                                                        : ''
                                                }`}
                                            >
                                                <Checkbox
                                                    checked={isChecked(
                                                        mod,
                                                        crujia.id,
                                                        sev,
                                                    )}
                                                    onCheckedChange={(
                                                        checked,
                                                    ) =>
                                                        setSeveridad(
                                                            globalIndex,
                                                            crujia.id,
                                                            sev,
                                                            Boolean(checked),
                                                        )
                                                    }
                                                />
                                            </td>
                                        )),
                                    )}
                                    {tieneOtros &&
                                        SEVERIDADES.map((sev, sevIndex) => (
                                            <td
                                                key={`${mod.codigo}-otros-${sev}`}
                                                className={`px-2 py-1.5 text-center ${
                                                    sevIndex === 0
                                                        ? 'border-l border-border/60'
                                                        : ''
                                                }`}
                                            >
                                                <Checkbox
                                                    checked={ otrosIds.some(
                                                            (id) =>
                                                                isChecked(
                                                                    mod,
                                                                    id,
                                                                    sev,
                                                                ),
                                                        )}
                                                    onCheckedChange={(
                                                        checked,
                                                    ) => {
                                                        for (const id of otrosIds) {
                                                            setSeveridad(
                                                                globalIndex,
                                                                id,
                                                                sev,
                                                                Boolean(
                                                                    checked,
                                                                ),
                                                            );
                                                        }
                                                    }}
                                                />
                                            </td>
                                        ))}
                                </tr>
                            );
                        })}
                </tbody>
            </table>
        </div>
    );
}
