'use client';
import {
  Table,
  TableHead,
  TableBody,
  TableCell,
  Typography,
  TableRow,
  IconButton,
  Button,
} from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import {  faLocationDot, faMap, } from '@fortawesome/free-solid-svg-icons';
import { Box } from '@mui/system';
import { useState } from 'react';

import { StyledTableContainer } from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import { HeaderCell, StyledTableRow } from '@/shared/components/form/style';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { BaseStyledRow, TrajetStyledRow } from '@/shared/sections/contract/styles';
import { VerificationTableType } from './weekly-verification-panel';
import VsnScheduleModal from '@/shared/sections/chauffeur/roadmap/components/validate-roadmap/vsn-schedule-modal/vsn-schedule-modal';
import GeolocModal from '@/shared/sections/chauffeur/roadmap/components/validate-roadmap/vsn-schedule-modal/geoloc-modal';
import SubbmitedRoadMapModal from '@/shared/sections/chauffeur/roadmap/components/validate-roadmap/vsn-schedule-modal/submitted-roadMap-modal';
import ConditionalComponent from '../table/ConditionalComponent';

interface Column {
  id: string;
  label: string;
  align?: 'left' | 'center' | 'right';
}

interface ScheduleVerificationTableProps {
  title: string;
  columns: Column[];
  data: any[];
  VerificationType: VerificationTableType;
  maxHeight?: string | number;
  dates: Date[];
}

export default function ScheduleVerificationTable({
  title,
  columns,
  data,
  VerificationType,
  maxHeight = '486px',
  dates,
}: ScheduleVerificationTableProps) {
  const [modalOpen, setModalOpen] = useState(false);

  const [planningModalOpen, setPlanningModalOpen] = useState(false);
  const [subbmitedRoadMapModalOpen, setSubbmitedRoadMapModalOpen] = useState(false);

  const [selectedRow, setSelectedRow] = useState<any>(null);

  const isCombinedTable = VerificationType === VerificationTableType.combinedTable;
  
  const handleOpenModal = (row: any) => {
    setSelectedRow(row);
    setModalOpen(true);
  };

  const handleCloseModal = () => {
    setModalOpen(false);
  };
  const handleCloseModalPlanning = () => {
    setPlanningModalOpen(false);
  };
  const handleCloseSubbmitedRoadMapModal = () => {
    setSubbmitedRoadMapModalOpen(false);
  };

  const renderCellContent = (columnId: string, value: any, row: any) => {
    const isGeolocation = VerificationType === VerificationTableType.geolocation;

    if (columnId === 'action') {
      const isVsn = VerificationType === VerificationTableType.vsnschedule;
      const isSubmitted = VerificationType === VerificationTableType.submittedRoadMap;
      if (isVsn) {
        return (
          <CustomTooltip title="Voir les détails" arrow>
            <IconButton
              onClick={() => {
                setSelectedRow(row);
                setPlanningModalOpen(true);
              }}
            >
              <FontAwesome icon={faLocationDot} color="primary.main" />
            </IconButton>
          </CustomTooltip>
        );
      }
      if (isSubmitted) {
        return (
          <CustomTooltip title="Voir les détails" arrow>
            <IconButton
              onClick={() => {
                setSelectedRow(row);
                setSubbmitedRoadMapModalOpen(true);
              }}
            >
              <FontAwesome icon={faMap} color="primary.main" />
            </IconButton>
          </CustomTooltip>
        );
      }
    }

    const isClickable = isGeolocation && columnId !== 'date';

    const handleClick = () => {
      if (isClickable) {
        const routeData = row.routes?.[columnId];
        if (routeData) {
          setSelectedRow({
            date: row.date,
            timeSlot: columnId,
            route: routeData,
            carRegistration: 'GH-571-WA',
          });
          setModalOpen(true);
        }
      }
    };

    const cellContent = (
      <Typography
        variant="caption"
        sx={{
          cursor: isClickable ? 'pointer' : 'default',
          color: isClickable ? 'primary.main' : 'inherit',
        }}
      >
        {value || '—'}
      </Typography>
    );

    return isClickable ? (
      <Box onClick={handleClick} sx={{ display: 'flex', alignItems: 'center' }}>
        {cellContent}
      </Box>
    ) : (
      cellContent
    );
  };

  const renderRow = (date: Date, index: number) => {
    const isoDate = date.toISOString().split('T')[0];
    const row = data.find((d) => d.date === isoDate) || { date: isoDate };

    return (
      <TrajetStyledRow key={index} sx={{ height: 70 }}>
        {columns.map((column) => {
          const value =
            column.id === 'date' ? isoDate : row[column.id] !== undefined ? row[column.id] : '—'; // or "" if you prefer empty

          return (
            <TableCell key={column.id} align={column.align} sx={{ whiteSpace: 'nowrap', py: 1.6 }}>
              {renderCellContent(column.id, value, row)}
            </TableCell>
          );
        })}
      </TrajetStyledRow>
    );
  };

  const fontSize = pxToRem(13);

  return (
    <>
      <StyledTableContainer
        sx={{
          maxHeight: maxHeight,
        }}
      >
        <Table stickyHeader>
          <TableHead>
            <TableRow sx={{ bgcolor: 'white' }}>
              <TableCell
                colSpan={columns.length}
                align="center"
                sx={{ fontWeight: 'bold', color: 'primary.main', position: 'sticky' }}
              >
                <Box display="flex" alignItems="center">
              
                <Typography variant="subtitle1" sx={{ flexGrow: 1, textAlign: 'center', fontWeight: 'bold' }}>
                {title || 'Planning VSN'}
              </Typography>
              <ConditionalComponent isValid={isCombinedTable} defaultComponent={null}>
                <Button
                  size="small"
                  variant="contained"
                  sx={{ ml: 1, textTransform: 'none' }}
                >
                  Synthèse
                </Button>
              </ConditionalComponent>
                </Box>
              </TableCell>
            </TableRow>
            <BaseStyledRow>
              {columns.map((headCell) => (
                <HeaderCell
                  sx={{
                    fontSize: fontSize,
                    position: 'sticky',
                    top: 57,
                    backgroundColor: 'primary.lighter',
                    py: 1.5,
                  }}
                  key={headCell.id}
                >
                  {headCell.label}
                </HeaderCell>
              ))}
            </BaseStyledRow>
          </TableHead>
          <TableBody>{dates?.map((date, index) => renderRow(date, index))}</TableBody>
        </Table>
      </StyledTableContainer>

      {selectedRow && selectedRow.route && (
        <GeolocModal
          open={modalOpen}
          onClose={handleCloseModal}
          timeDetails={{
            departureDate: new Date(`${selectedRow.date}T${selectedRow.route.startHour}`),
            arrivalDate: new Date(`${selectedRow.date}T${selectedRow.route.endHour}`),
            carRegistration: selectedRow.carRegistration,
            distance: selectedRow.route.distance,
            departureLocation: selectedRow.route.departureAddress,
            arrivalLocation: selectedRow.route.arrivalAddress,
          }}
        />
      )}

      <VsnScheduleModal open={planningModalOpen} onClose={handleCloseModalPlanning} />
      {selectedRow && (
        <SubbmitedRoadMapModal
          open={subbmitedRoadMapModalOpen}
          onClose={handleCloseSubbmitedRoadMapModal}
          startKm={selectedRow?.startMileage | 0}
          endKm={selectedRow?.endMileage | 0}
          fuelAmount={selectedRow?.fuelAmount | 0}
          observation={selectedRow?.observation ?? ""}
          otherTrips={selectedRow?.otherTrips ?? []}
        />
      )}
    </>
  );
}
