'use client';

import type React from 'react';
import { useEffect, useState } from 'react';
import { Box, Grid, Typography, MenuItem, Select, TextField, IconButton, alpha, Button } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faPlus, faTrash, faXmark } from '@fortawesome/free-solid-svg-icons';
import { faCircleCheck } from '@fortawesome/free-regular-svg-icons';
import { HOLIDAY_TYPE_OPTIONS, HolidayType, IHolidayImport, IHolidayImportChildren, IHolidayZoneImport } from '@/shared/types/establishment';
import { DateTimePicker } from '@mui/x-date-pickers';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

export const ZONES_OPTIONS = [
  { value: 'Zone A', label: 'Zone A' },
  { value: 'Zone B', label: 'Zone B' },
  { value: 'Zone C', label: 'Zone C' },
];

export const ZONES_IMPORT_DEFAULT = [
  { zoneName: "Zone A", holidays: [] },
  { zoneName: "Zone B", holidays: [] },
  { zoneName: "Zone C", holidays: [] },
]

export const ACADEMIES: string[] = [
  "Lyon", "Orleans", "Paris", "Toulouse", "Nice"
];

export const STUDENT_POPULATIONS: string[] = [
  "-", "Élèves", "Élèves des collèges", "Élèves du premier degré", "Élèves du second degré", "Élèves des lycées"
];

export const HOLIDAY_FILE_TYPE_OPTIONS = [
  { value: "Jour férié", label: "Jour férié" },
  { value: "Vacance scolaire", label: "Vacance scolaire" },
]

interface HolidayZoneDetailsProps {
  formData: IHolidayImport;
  setFormData: React.Dispatch<React.SetStateAction<IHolidayImport>>;
  isReadOnly: boolean;
}

export default function HolidayZoneDetails({
  formData,
  setFormData,
  isReadOnly
}: HolidayZoneDetailsProps) {
  const [zones, setZones] = useState<IHolidayZoneImport[]>(formData.zones.length > 0 ? formData.zones : ZONES_IMPORT_DEFAULT);
  const [editingRow, setEditingRow] = useState<{ zoneName: string; vacationId: string } | null>(null);
  const [tempValues, setTempValues] = useState<Partial<IHolidayImportChildren>>({});
  const [tempNewRows, setTempNewRows] = useState<Record<string, IHolidayImportChildren[]>>({});

  useEffect(() => {
    console.log('formData.zones:', formData.zones);
    if (formData.zones.length > 0) {
      setZones(formData.zones);
    }
  }, [formData.zones]);

  useEffect(() => {
    console.log('zones state:', zones);
    setFormData((prev) => ({ ...prev, zones }));
  }, [zones, setFormData]);

  const createVacation = (zoneName: string): IHolidayImportChildren => ({
    id: `0`,
    name: '',
    startDate: '',
    endDate: '',
    type: HOLIDAY_FILE_TYPE_OPTIONS[0].value,
    academy: '',
    population: '',
    zoneName: zoneName,
  });

  const handleAddVacation = (zoneName: string) => {
    const newId = Date.now().toString();
    setTempNewRows((prev) => ({
      ...prev,
      [zoneName]: [
        ...(prev[zoneName] || []),
        {
          ...createVacation(zoneName),
          id: newId,
        },
      ],
    }));
    setEditingRow({ zoneName, vacationId: newId });
    setTempValues({});
  };

  const handleRemoveVacation = (zoneName: string, vacationId: string) => {
    setZones((prevZones) =>
      prevZones.map((zone) =>
        zone.zoneName === zoneName
          ? { ...zone, holidays: zone.holidays.filter((h) => h.id !== vacationId) }
          : zone
      )
    );
  };

  const handleStartEditing = (zoneName: string, vacationId: string) => {
    if (isReadOnly) return;

    const zone = zones.find((z) => z.zoneName === zoneName);
    const vacation = zone?.holidays.find((h) => h.id === vacationId);

    if (zone && vacation) {
      setTempValues({
        name: vacation.name,
        startDate: vacation.startDate,
        endDate: vacation.endDate,
        type: vacation.type,
        academy: vacation.academy,
        population: vacation.population,
        zoneName: vacation.zoneName,
      });
      setEditingRow({ zoneName, vacationId });
    }
  };

  const handleSaveEdit = () => {
    if (!editingRow) return;
    const { zoneName, vacationId } = editingRow;
    if (typeof vacationId === 'number' && (tempNewRows[zoneName] || []).some(row => row.id === vacationId)) {
      const tempRow = (tempNewRows[zoneName] || []).find((row) => row.id === vacationId);
      if (!tempRow) return;
      const newId = Date.now().toString();
      setZones((prevZones) =>
        prevZones.map((zone) =>
          zone.zoneName === zoneName
            ? {
              ...zone,
              holidays: [
                ...zone.holidays,
                {
                  ...tempRow,
                  ...tempValues,
                  id: newId,
                },
              ],
            }
            : zone
        )
      );
      setTempNewRows((prev) => ({
        ...prev,
        [zoneName]: (prev[zoneName] || []).filter((row) => row.id !== vacationId),
      }));
    } else {
      setZones((prevZones) =>
        prevZones.map((zone) =>
          zone.zoneName === zoneName
            ? {
              ...zone,
              holidays: zone.holidays.map((holiday) =>
                holiday.id === vacationId
                  ? {
                    ...holiday,
                    name: tempValues.name || holiday.name,
                    startDate: tempValues.startDate || holiday.startDate,
                    endDate: tempValues.endDate || holiday.endDate,
                    type: tempValues.type || holiday.type,
                    academy: tempValues.academy || holiday.academy,
                    population: tempValues.population || holiday.population,
                    zoneName: tempValues.zoneName || holiday.zoneName,
                  }
                  : holiday
              ),
            }
            : zone
        )
      );
    }
    setEditingRow(null);
    setTempValues({});
  };

  const handleCancelEdit = () => {
    if (editingRow && typeof editingRow.vacationId === 'number') {
      setTempNewRows((prev) => ({
        ...prev,
        [editingRow.zoneName]: (prev[editingRow.zoneName] || []).filter((row) => row.id !== editingRow.vacationId),
      }));
    }
    setEditingRow(null);
    setTempValues({});
  };

  const handleTempValueChange = (field: keyof IHolidayImportChildren, value: string) => {
    setTempValues((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const renderCell = (zone: IHolidayZoneImport, holiday: IHolidayImportChildren, field: keyof IHolidayImportChildren) => {
    const isEditing =
      editingRow && editingRow.zoneName === zone.zoneName && editingRow.vacationId === holiday.id;

    if (isEditing) {
      if (field === 'name') {
        return (
          <TextField
            fullWidth
            size="small"
            autoFocus={field === 'name'}
            value={tempValues.name || holiday.name}
            onChange={(e) => handleTempValueChange('name', e.target.value)}
          />
        );
      } else if (field === 'startDate') {
        return (
          <DateTimePicker
            value={tempValues.startDate ? new Date(tempValues.startDate) : holiday.startDate ? new Date(holiday.startDate) : null}
            onChange={(date) => handleTempValueChange('startDate', date ? date.toISOString() : '')}
            views={['year', 'month', 'day', 'hours', 'minutes']}
            openTo="year"
            readOnly={isReadOnly}
            slotProps={{
              textField: (params) => ({
                ...params,
                fullWidth: true,
                placeholder: 'DD/MM/YYYY',
                InputLabelProps: {
                  shrink: true,
                },
                size: 'small',
              }),
              actionBar: {
                actions: ['clear', 'today'],
              },
            }}
          />
        );
      } else if (field === 'endDate') {
        return (
          <DateTimePicker
            value={tempValues.endDate ? new Date(tempValues.endDate) : holiday.endDate ? new Date(holiday.endDate) : null}
            onChange={(date) => handleTempValueChange('endDate', date ? date.toISOString() : '')}
            views={['year', 'month', 'day', 'hours', 'minutes']}
            openTo="year"
            readOnly={isReadOnly}
            slotProps={{
              textField: (params) => ({
                ...params,
                fullWidth: true,
                placeholder: 'DD/MM/YYYY',
                InputLabelProps: {
                  shrink: true,
                },
                size: 'small',
              }),
              actionBar: {
                actions: ['clear', 'today'],
              },
            }}
          />
        );
      } else if (field === 'type') {
        return (
          <Select
            fullWidth
            size="small"
            value={tempValues.type || holiday.type || HOLIDAY_FILE_TYPE_OPTIONS[0].value}
            onChange={(e) => handleTempValueChange('type', e.target.value)}
          >
            {HOLIDAY_FILE_TYPE_OPTIONS.map((type) => (
              <MenuItem key={type.value} value={type.value}>
                {type.label}
              </MenuItem>
            ))}
          </Select>
        );
      } else if (field === 'academy') {
        return (
          <Select
            fullWidth
            size="small"
            value={tempValues.academy || holiday.academy || ACADEMIES[0]}
            onChange={(e) => handleTempValueChange('academy', e.target.value)}
          >
            {ACADEMIES.map((academy) => (
              <MenuItem key={academy} value={academy}>
                {academy}
              </MenuItem>
            ))}
          </Select>
        );
      } else if (field === 'population') {
        return (
          <Select
            fullWidth
            size="small"
            value={tempValues.population || holiday.population || STUDENT_POPULATIONS[0]}
            onChange={(e) => handleTempValueChange('population', e.target.value)}
          >
            {STUDENT_POPULATIONS.map((population) => (
              <MenuItem key={population} value={population}>
                {population}
              </MenuItem>
            ))}
          </Select>
        );
      }
    } else {
      return (
        <Box
          sx={{
            p: 1,
            cursor: isReadOnly ? 'default' : 'pointer',
            '&:hover': {
              bgcolor: isReadOnly ? 'transparent' : 'rgba(0, 0, 0, 0.04)',
            },
          }}
          onDoubleClick={() => handleStartEditing(zone.zoneName, holiday.id)}
        >
          <Typography variant="body2">{holiday[field] || '-'}</Typography>
        </Box>
      );
    }
  };

  const renderVacationRow = (zone: IHolidayZoneImport, holiday: IHolidayImportChildren) => {
    const isEditing =
      editingRow && editingRow.zoneName === zone.zoneName && editingRow.vacationId === holiday.id;

    return (
      <Box
        key={`vacation-${holiday.id}-${formData.id}`}
        sx={{
          backgroundColor: 'primary.lighter',
          borderRadius: '8px',
          p: 1,
          mb: 0.5,
        }}
      >
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'name')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'startDate')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'endDate')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'type')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'academy')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, holiday, 'population')}
          </Grid>
          <Grid item xs={1}>
            <ConditionalComponent isValid={!isReadOnly}>
              <Box sx={{ display: "flex", gap: 1, justifyContent: "center" }}>
                <ConditionalComponent isValid={isEditing || false}>
                  <>
                    <IconButton size="small" color="primary" onClick={handleSaveEdit} sx={{ minWidth: "auto", p: 0 }}>
                      <FontAwesome icon={faCircleCheck} width={16} />
                    </IconButton>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={handleCancelEdit}
                      sx={{ minWidth: "auto", p: 0 }}
                    >
                      <FontAwesome icon={faXmark} width={16} />
                    </IconButton>
                  </>
                </ConditionalComponent>
                <ConditionalComponent isValid={!isEditing}>
                  <IconButton
                    size="small"
                    color="error"
                    onClick={() => handleRemoveVacation(zone.zoneName, holiday.id)}
                    sx={{ minWidth: "auto", p: 0 }}
                  >
                    <FontAwesome icon={faTrash} width={14} />
                  </IconButton>
                </ConditionalComponent>
              </Box>
            </ConditionalComponent>
          </Grid>
        </Grid>
      </Box>
    );
  };

  const renderZoneHeader = (zone: IHolidayZoneImport) => (
    <Box
      sx={{
        backgroundColor: 'primary.lighter',
        borderRadius: '8px',
        mb: 1,
        p: 2,
      }}
    >
      <Typography variant="body2" sx={{ pb: 2, textAlign: 'center', color: 'text.secondary' }}>
        {zone.zoneName}
      </Typography>
      <Grid container spacing={2}>
        {['Nom', 'Date de début', 'Date de fin', 'Type', 'Académie', 'Population'].map((header, index) => (
          <Grid item xs={2} key={header}>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {header}
            </Typography>
          </Grid>
        ))}
        <Grid item xs={1} sx={{ display: 'flex', justifyContent: 'center' }}>
          {!isReadOnly ? (
            <IconButton
              size="small"
              onClick={() => handleAddVacation(zone.zoneName)}
              sx={{ minWidth: 'auto', p: 0 }}
            >
              <FontAwesome icon={faPlus} width={14} />
            </IconButton>
          ) : <></>}
        </Grid>
      </Grid>
    </Box>
  );

  const renderEmptyState = () => (
    <Box
      sx={{
        bgcolor: (theme) => alpha(theme.palette.grey[500], 0.04),
        borderRadius: '8px',
        p: 1.5,
        mb: 2,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Typography variant="body2" sx={{ color: 'text.disabled' }}>
        {!isReadOnly ? 'Cliquez sur + pour ajouter une période' : 'Aucune période définie'}
      </Typography>
    </Box>
  );

  const renderZone = (zone: IHolidayZoneImport) => {
    const tempRows = tempNewRows[zone.zoneName] || [];
    return (
      <Grid item xs={12} sm={12} key={`zone-${zone.zoneName}-${formData.id}`}>
        {renderZoneHeader(zone)}
        {zone.holidays.length > 0
          ? zone.holidays.map((holiday) => renderVacationRow(zone, holiday))
          : null}
        {tempRows.map((holiday) =>
          renderVacationRow(zone, holiday)
        )}
        {zone.holidays.length === 0 && tempRows.length === 0 && renderEmptyState()}
      </Grid>
    );
  };

  return (
    <Box>
      <Grid container spacing={4}>
        <Grid container item spacing={2}>
          {zones.map((zone) => renderZone(zone))}
        </Grid>
      </Grid>
    </Box>
  );
}