'use client';

import type React from 'react';

import { useEffect, useState } from 'react';
import {
  Box,
  Grid,
  Typography,
  MenuItem,
  Select,
  TextField,
  IconButton,
  alpha,
} from '@mui/material';
import { VacationType, type IFileImport, type Zone, type ZoneVacation } from '@/shared/types/vacance';
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 { Months } from '@/shared/types/etablissement';
import { DEFAULT_ZONES } from '@/shared/_mock/_vacance';

interface ZoneDetailsProps {
  formData: IFileImport;
  setFormData: React.Dispatch<React.SetStateAction<IFileImport>>;
  isReadOnly: boolean;
}

export default function ZoneDetails({
  formData,
  setFormData,
  isReadOnly,
}: ZoneDetailsProps) {
  const [zones, setZones] = useState<Zone[]>(formData.zones || DEFAULT_ZONES);
  const [editingRow, setEditingRow] = useState<{ zoneId: string; vacationId: string } | null>(null);
  const [tempValues, setTempValues] = useState<Partial<ZoneVacation>>({});

  useEffect(() => {
    setFormData((prev) => ({ ...prev, zones }));
  }, [zones, setFormData]);

  const createVacation = (): ZoneVacation => ({
    id: `vacation-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    mois: '',
    de: '',
    a: '',
    type: '',
  });

  const handleAddVacation = (zoneId: string) => {
    setZones((prevZones) =>
      prevZones.map((zone) =>
        zone.id === zoneId ? { ...zone, vacations: [...zone.vacations, createVacation()] } : zone
      )
    );
  };

  const handleRemoveVacation = (zoneId: string, vacationId: string) => {
    setZones((prevZones) =>
      prevZones.map((zone) =>
        zone.id === zoneId
          ? { ...zone, vacations: zone.vacations.filter((v) => v.id !== vacationId) }
          : zone
      )
    );
  };

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

    const zone = zones.find((z) => z.id === zoneId);
    const vacation = zone?.vacations.find((v) => v.id === vacationId);

    if (zone && vacation) {
      setTempValues({
        mois: vacation.mois,
        de: vacation.de,
        a: vacation.a,
        type: vacation.type,
      });
      setEditingRow({ zoneId, vacationId });
    }
  };

  const handleSaveEdit = () => {
    if (!editingRow) return;

    const { zoneId, vacationId } = editingRow;

    setZones((prevZones) =>
      prevZones.map((zone) =>
        zone.id === zoneId
          ? {
              ...zone,
              vacations: zone.vacations.map((vacation) =>
                vacation.id === vacationId
                  ? {
                      ...vacation,
                      mois: tempValues.mois || vacation.mois,
                      de: tempValues.de || vacation.de,
                      a: tempValues.a || vacation.a,
                      type: tempValues.type || vacation.type,
                    }
                  : vacation
              ),
            }
          : zone
      )
    );

    setEditingRow(null);
    setTempValues({});
  };

  const handleCancelEdit = () => {
    setEditingRow(null);
    setTempValues({});
  };

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

  const renderCell = (zone: Zone, vacation: ZoneVacation, field: keyof ZoneVacation) => {
    const isEditing =
      editingRow && editingRow.zoneId === zone.id && editingRow.vacationId === vacation.id;

    if (isEditing) {
      if (field === 'mois') {
        return (
          <Select
            fullWidth
            size="small"
            value={tempValues.mois || vacation.mois}
            onChange={(e) => handleTempValueChange('mois', e.target.value)}
            autoFocus={field === 'mois'}
          >
            {Object.values(Months).map((month) => (
              <MenuItem key={month} value={month}>
                {month}
              </MenuItem>
            ))}
          </Select>
        );
      } else if (field === 'type') {
        return (
          <Select
            fullWidth
            size="small"
            value={tempValues.type || vacation.type}
            onChange={(e) => handleTempValueChange('type', e.target.value)}
          >
            {Object.values(VacationType).map((type) => (
              <MenuItem key={type} value={type}>
                {type}
              </MenuItem>
            ))}
          </Select>
        );
      } else {
        return (
          <TextField
            fullWidth
            size="small"
            type="number"
            inputProps={{ min: 1, max: 31 }}
            value={tempValues[field] || vacation[field]}
            onChange={(e) => handleTempValueChange(field, e.target.value)}
          />
        );
      }
    } else {
      return (
        <Box
          sx={{
            p: 1,
            cursor: isReadOnly ? 'default' : 'pointer',
            '&:hover': {
              bgcolor: isReadOnly ? 'transparent' : 'rgba(0, 0, 0, 0.04)',
            },
          }}
          onDoubleClick={() => handleStartEditing(zone.id, vacation.id)}
        >
          <Typography variant="body2">{vacation[field] || '-'}</Typography>
        </Box>
      );
    }
  };

  const renderVacationRow = (zone: Zone, vacation: ZoneVacation) => {
    const isEditing =
      editingRow && editingRow.zoneId === zone.id && editingRow.vacationId === vacation.id;

    return (
      <Box
        key={`vacation-${vacation.id}-${formData.id}`}
        sx={{
          backgroundColor: 'primary.lighter',
          borderRadius: '8px',
          p: 1,
          mb: 0.5,
        }}
      >
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={3}>
            {renderCell(zone, vacation, 'mois')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, vacation, 'de')}
          </Grid>
          <Grid item xs={2}>
            {renderCell(zone, vacation, 'a')}
          </Grid>
          <Grid item xs={4}>
            {renderCell(zone, vacation, 'type')}
          </Grid>
          <Grid item xs={1}>
      {!isReadOnly ? (
        <Box sx={{ display: "flex", gap: 1, justifyContent: "center" }}>
          {isEditing ? (
            <>
              <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>
            </>
          ) : (
            <IconButton
              size="small"
              color="error"
              onClick={() => handleRemoveVacation(zone.id, vacation.id)}
              sx={{ minWidth: "auto", p: 0 }}
            >
              <FontAwesome icon={faTrash} width={14} />
            </IconButton>
          )}
        </Box>
      ) : <></>}
    </Grid>
        </Grid>
      </Box>
    );
  };

  const renderZoneHeader = (zone: Zone) => (
    <Box
      sx={{
        backgroundColor: 'primary.lighter',
        borderRadius: '8px',
        mb: 1,
        p: 2,
      }}
    >
      <Typography variant="body2" sx={{ pb: 2, textAlign: 'center', color: 'text.secondary' }}>
        {zone.name}
      </Typography>
      <Grid container spacing={2}>
        {['Mois', 'De', 'À', 'Type'].map((header, index) => (
          <Grid item xs={index === 0 ? 3 : index === 3 ? 4 : 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.id)}
              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: Zone) => (
    <Grid item xs={12} sm={6} key={`zone-${zone.id}-${formData.id}`}>
      {renderZoneHeader(zone)}

      {zone.vacations.length > 0
        ? zone.vacations.map((vacation) => renderVacationRow(zone, vacation))
        : renderEmptyState()}
    </Grid>
  );

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