'use client';

import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import RoadMapValidationTable from '@/shared/components/roadmap/roadmap-validation-table';
import RoadMapValidationTableFinal from '@/shared/components/roadmap/roadmap-validation-table-final';
import { CustomColumn } from '@/shared/components/roadmap/types';
import { ValidatedRoadMapTable } from '@/shared/types/roadMap';
import { Box } from '@mui/material';
import { useEffect, useState } from 'react';

export interface ValidationTableConfig {
  trajets: {
    id: string;
    label: string;
  }[];
  additionalColumns?: {
    id: string;
    label: string;
    align?: 'left' | 'center' | 'right';
  }[];
  dates: string[];
}

export default function ValidationTableFinal({
  tableConfig,
}: {
  tableConfig: ValidationTableConfig;
}) {
  const hasAdditionalColumns =
    tableConfig.additionalColumns && tableConfig.additionalColumns.length > 0;
  const [dates, setDates] = useState<Date[]>([]);
  const [validatedRoadMapTableData, setValidatedRoadMapTableData] = useState<
    ValidatedRoadMapTable | null | undefined
  >(undefined);

  const validatedRoadMapTable = useRoadMapStore((state) => state.validatedRoadMapDetails);
  const getValidedRoadmap = useRoadMapStore((state) => state.getValidedRoadmap);

  const generateColumns = (): CustomColumn[] => {
    const columns: CustomColumn[] = [{ id: 'date', label: '', colSpan: 1 }];

    tableConfig.trajets.forEach((trajet) => {
      columns.push({
        id: `trajet_${trajet.id}`,
        label: trajet.label,
        subColumns: [
          { id: `trajet_${trajet.id}_debut`, label: 'Début', align: 'center' },
          { id: `trajet_${trajet.id}_fin`, label: 'Fin', align: 'center' },
        ],
      });
    });

    if (hasAdditionalColumns) {
      tableConfig.additionalColumns!.forEach((column) => {
        columns.push({
          id: column.id,
          label: column.label,
        });
      });
    }

    return columns;
  };

  const generateData = () => {
    const baseRows = [
      ['09:04', '09:26', '17:08', '17:14', '18:32', '18:36', '20:21', '20:49'],
      ['10:52', '10:56', '12:01', '12:22', '18:50', '18:59', '21:40', '21:58'],
      ['06:12', '06:27', '13:20', '13:29', '18:36', '18:51', '23:13', '23:58'],
    ];

    const data = baseRows.map((trajets, index) => {
      const row: any = { id: index + 1, date: tableConfig.dates[index] };

      for (let i = 0; i < 4; i++) {
        row[`trajet_${i + 1}_debut`] = trajets[i * 2] || '';
        row[`trajet_${i + 1}_fin`] = trajets[i * 2 + 1] || '';
      }

      if (hasAdditionalColumns) {
        tableConfig.additionalColumns!.forEach((column) => {
          row[column.id] =
            column.id === 'total_journee'
              ? '00:00'
              : column.id === 'total_centiemes'
                ? '00:00'
                : column.id === 'deduction'
                  ? '0.00'
                  : column.id === 'heures_payees'
                    ? '0.00'
                    : column.id === 'delta_forfait'
                      ? '0.00'
                      : column.id === 'forfait'
                        ? '00:00'
                        : column.id === 'heures_nuit'
                          ? '00:00'
                          : column.id === 'heures_attente'
                            ? 0
                            : column.id === 'nb_vacation'
                              ? 0
                              : '';
        });
      }

      return row;
    });

    // Ligne de total semaine
    const totalRow: any = { id: 'total', date: '' };
    for (let i = 1; i <= 4; i++) {
      totalRow[`trajet_${i}_debut`] = '';
      totalRow[`trajet_${i}_fin`] = '';
    }
    if (hasAdditionalColumns) {
    }
    data.push(totalRow);

    return data;
  };

  const columns = generateColumns();
  const data = generateData();
  const getDaysInMonth = (date: Date | undefined): Date[] => {
    if (!date) return [];
    const year = date.getFullYear();
    const month = date.getMonth();
    const daysInMonth = new Date(year, month + 1, 0).getDate();

    return Array.from({ length: daysInMonth }, (_, i) => new Date(year, month, i + 1));
  };

  useEffect(() => {
    setDates(getDaysInMonth(new Date(2025, 5, 1)));

    const fetchValidatedData = async () => {
      await getValidedRoadmap(4);
    };

    fetchValidatedData();
  }, []);

  return (
    <Box sx={{ width: '100%' }}>
      <RoadMapValidationTableFinal
        validatedRoadMapTable={validatedRoadMapTable as ValidatedRoadMapTable | undefined}
        dates={dates}
        isFinalResult={hasAdditionalColumns}
        columns={columns}
        data={data}
        maxHeight="600px"
      />
    </Box>
  );
}
