'use client';

import React, { useEffect, useState } from 'react';
import {
  Radio,
  RadioGroup,
  FormControlLabel,
  Typography,
  Grid,
  Box,
  CircularProgress,
} from '@mui/material';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { fr } from 'date-fns/locale';
import { FormikTouched, useFormik } from 'formik';
import { useTeamStore } from '@/shared/api/stores/teamStore';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { formFields } from '../utils/form-fields-equipe';
import { ScrollBox } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import { IDepartment, IEquipe, TEAM_STATUS, TeamList, TeamRequest, TeamStatus } from '@/shared/types/equipe';
import { useSnackbar } from 'notistack';
import { equipeSchema } from '../utils/equipe-schema';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import EquipeAgentsTable from '../components/equipe-agents-list';

interface EquipeFormProps {
  equipe: IEquipe;
  mode: ModeType;
  onSave?: (updatedTeam: TeamList) => void;
  onEdit: (updatedTeam: IEquipe) => void;
  onClose: (forceClose: boolean) => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges?: (value: boolean) => void;
  updateTabContent?: (tabId: string, newContent: TeamList | IEquipe) => void;
  tabId?: string;
  refreshData?: () => void;
}

export default function EquipeForm({
  equipe,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
  refreshData,
}: EquipeFormProps) {
  const isReadOnly = mode === 'view';
  const { enqueueSnackbar } = useSnackbar();
  const {
    createTeam,
    loading: teamLoading,
    updateTeam,
    getTeamById,
    removeMember,
    duplicateTeam,
    exportTeams,
    getCollaboratorsWithoutTeam,
    collaboratorsWithoutTeam,
    teamById,
  } = useTeamStore();
  const { departmentNames, fetchDepartmentNames, loading: deptLoading } = useInfrastructureStore();
  const [teamLeaderOptions, setTeamLeaderOptions] = useState<{ value: string; label: string }[]>([]);
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [initialValues, setInitialValues] = useState<TeamRequest>({
    name: '',
    teamLeaderId: 0,
    department: { id: 0 },
    collaborators: [],
    creationDate: new Date().toISOString().split('T')[0],
    status: TeamStatus.ACTIVE,
  });

 useEffect(() => {
  let options = collaboratorsWithoutTeam.map((user) => ({
    value: String(user.id),
    label: `${user.firstName} ${user.lastName}`,
  }));
  if (mode !== 'copy' && teamById?.teamLeaderId && teamById?.collaborators) {
    const teamLeader = teamById.collaborators.find((c) => c.id === teamById.teamLeaderId);
    if (teamLeader && !options.some((opt) => opt.value === String(teamLeader.id))) {
      options.push({
        value: String(teamLeader.id),
        label: `${teamLeader.firstName} ${teamLeader.lastName}`,
      });
    }
  }

  setTeamLeaderOptions(options);
}, [collaboratorsWithoutTeam, teamById, mode]); 

  useEffect(() => {
    if (departmentNames.length > 0) {
      setDepartmentOptions(
        departmentNames.map((dept: any) => ({
          value: String(dept.id),
          label: dept.name,
        }))
      );
    }
  }, [departmentNames]);

const handleRemoveAgent = async (agentId: string) => {
  try {
    const updatedCollaborators = formik.values.collaborators?.filter(
      (collaborator) => String(collaborator.id) !== agentId
    ) || [];

    if (mode === 'add') {
      formik.setFieldValue('collaborators', updatedCollaborators);
      enqueueSnackbar('Membre retiré de la liste', { variant: 'success' });
    } else if (equipe.id) {

      await removeMember(Number(equipe.id), Number(agentId));
      formik.setFieldValue('collaborators', updatedCollaborators);
      enqueueSnackbar('Membre supprimé avec succès', { variant: 'success' });
    }
  } catch (error: any) {
    enqueueSnackbar(error.message || 'Erreur lors de la suppression du membre', {
      variant: 'error',
    });
  }
};
  const getInitialValues = async () => {
    try {
      if (equipe.id) {
        const team = await getTeamById(String(equipe.id));
        if (team) {
          await Promise.all([getCollaboratorsWithoutTeam(), fetchDepartmentNames()]);
          setInitialValues({
            id: team.id,
            name: team.name,
            teamLeaderId: mode === 'copy' ? 0 : team.teamLeaderId ? Number(team.teamLeaderId) : 0,
            department: team.department ? { id: Number(team.department.id) } : { id: 0 },
            collaborators: mode === 'copy' ? [] : team.collaborators?.map((collaborator) => ({
            id: Number(collaborator.id),
            firstName: collaborator.firstName,
            lastName: collaborator.lastName
          })) || [],
            creationDate: team.creationDate,
            teamLeaderFullName:team.teamLeaderFullName,
            status: team.status,
            teamCode: team.teamCode,
          });
        }
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de la récupération des données de l'équipe", {
        variant: 'error',
      });
    }
  };

  useEffect(() => {
    if (equipe.id && (mode === 'view' || mode === 'edit' || mode === 'copy')) {
      getInitialValues();
    } else {
      Promise.all([getCollaboratorsWithoutTeam(), fetchDepartmentNames()]);
    }
  }, [equipe.id, mode]);

  const handleFormSubmit = async (values: TeamRequest) => {
    try {
      const teamData: TeamRequest = {
        name: values.name,
        teamLeaderId: Number(values.teamLeaderId),
        department: { id: Number(values.department.id) },
        collaborators: values.collaborators.map((collaborator) => ({
          id: typeof collaborator === 'string' ? Number(collaborator) : Number(collaborator.id),
        })),
        creationDate: values.creationDate.split('T')[0],
        status: values.status,
      };

      if (mode === 'add') {
        await createTeam(teamData);
        enqueueSnackbar('Équipe créée avec succès', { variant: 'success' });
      } else if (mode === 'copy') {
        await duplicateTeam(String(equipe.id), teamData);
        enqueueSnackbar('Équipe dupliquée avec succès', { variant: 'success' });
      } else if (mode === 'edit') {
        console.log("date is : ",teamData.creationDate)
        teamData.id = String(equipe.id);
        teamData.teamCode = equipe.teamCode;
        await updateTeam(teamData);
        enqueueSnackbar('Équipe modifiée avec succès', { variant: 'success' });
      }

      refreshData && refreshData();
      onClose(false);
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la création/modification de l'équipe", {
        variant: 'error',
      });
    }
  };

  const handleExportEquipe = () => {
    if (equipe?.id) {
      exportTeams({ id: equipe.id });
    }
  };

  const formik = useFormik<TeamRequest>({
    initialValues,
    validationSchema: equipeSchema,
    enableReinitialize: true,
    onSubmit: handleFormSubmit,
  });

  const loading = teamLoading || deptLoading;

  const handleSave = () => {
    formik.validateForm().then((errors) => {
      const hasErrors = Object.keys(errors).length > 0;
      console.log('Form errors:', errors);
      if (!hasErrors) {
        formik.submitForm();
      } else {
        const touchedFields: FormikTouched<TeamRequest> = {
          name: true,
          teamLeaderId: true,
          department: { id: true },
          collaborators: formik.values.collaborators?.map(() => ({ id: true })) || [],
          status: true,
        };
        formik.setTouched(touchedFields);
      }
    });
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress />
      </Box>
    );
  }

  const handleChange = (name: string, value: any) => {
    if (name === 'teamLeaderId') {
      const numericValue = Number(value);
      formik.setFieldValue('teamLeaderId', isNaN(numericValue) ? 0 : numericValue);
    } else if (name === 'department') {
      const numericValue = Number(value);
      formik.setFieldValue('department', isNaN(numericValue) ? { id: 0 } : { id: numericValue });
    } else {
      formik.setFieldValue(name, value);
    }
  };

const renderField = (field: FormFieldType<TeamRequest>) => {
  if (field.name === 'collaborators') {
    const collaboratorOptions = collaboratorsWithoutTeam.map((agent) => ({
      value: String(agent.id),
      label: `${agent.firstName} ${agent.lastName}`,
    }));
    const existingCollaborators = formik.values.collaborators || [];
    existingCollaborators.forEach((collaborator) => {
      if (!collaboratorOptions.some((opt) => opt.value === String(collaborator.id))) {
        collaboratorOptions.push({
          value: String(collaborator.id),
          label: `${collaborator.firstName} ${collaborator.lastName}`,
        });
      }
    });

    return (
      <FormField
        field={{
          ...field,
          name: 'collaborators',
          type: 'multiple',
          options: collaboratorOptions,
        }}
        value={formik.values.collaborators?.map((collaborator) => String(collaborator.id)) || []}
        onChange={(name, selectedIds) => {
          const selectedCollaborators = selectedIds.map((id: string) => {
            const collaborator = collaboratorsWithoutTeam.find((agent) => String(agent.id) === id) || 
                                formik.values.collaborators.find((c) => String(c.id) === id);
            return {
              id: Number(id),
              firstName: collaborator?.firstName || '',
              lastName: collaborator?.lastName || '',
            };
          });
          formik.setFieldValue('collaborators', selectedCollaborators);
        }}
        error={
          formik.touched.collaborators ? (formik.errors.collaborators as string) : undefined
        }
        onBlur={formik.handleBlur}
        isReadOnly={isReadOnly}
      />
    );
  }

  return (
    <FormField
      field={field}
      value={
        field.name === 'teamLeaderId'
          ? String(formik.values.teamLeaderId || '')
          : field.name === 'department'
          ? String(formik.values.department?.id || '')
          : formik.values[field.name as keyof TeamRequest] || ''
      }
      onChange={(name, value) => handleChange(name, value)}
      error={
        formik.touched[field.name as keyof TeamRequest]
          ? (formik.errors[field.name as keyof TeamRequest] as string)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  );
};
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <ScrollBox
        sx={{
          mb: '15px',
          width: '100%',
          overflow: 'auto',
          position: 'relative',
        }}
      >
        <Box
          sx={{
            backgroundColor: 'white',
            borderBottomRightRadius: '10px',
            borderBottomLeftRadius: '10px',
            borderTopRightRadius: '10px',
          }}
          pt={isReadOnly ? 2 : 4}
          pb={3}
          px={6}
        >
          <ConditionalComponent isValid={isReadOnly}>
            <EditExportButtons
              onEdit={() => onEdit(equipe)}
              onExport={() => handleExportEquipe()}
              tooltipTitle="l'équipe"
            />
          </ConditionalComponent>

          <form onSubmit={formik.handleSubmit}>
            <Grid container spacing={5}>
              {formFields(teamLeaderOptions, departmentOptions).map((field) => (
                <Grid item xs={12} sm={4} key={field.name}>
                  {renderField(field)}
                </Grid>
              ))}

              <Grid item xs={12}>
                <Box display="flex" alignItems="center" gap={4}>
                  <Typography sx={{ color: isReadOnly ? 'text.disabled' : 'primary.main' }}>
                    Statut
                  </Typography>
                  <RadioGroup
                    row
                    name="status"
                    value={formik.values.status}
                    onChange={formik.handleChange}
                  >
                    {TEAM_STATUS.map((option: any) => (
                      <FormControlLabel
                        key={option.value}
                        value={option.value}
                        control={<Radio />}
                        label={option.label}
                        disabled={isReadOnly}
                        sx={{
                          '& .MuiFormControlLabel-label': {
                            color: formik.values.status === option.value ? 'primary.main' : 'inherit',
                          },
                        }}
                      />
                    ))}
                  </RadioGroup>
                </Box>
              </Grid>
              <ConditionalComponent isValid={!isReadOnly}>
                <Grid item xs={12}>
                  <ActionButtons
                    onSave={handleSave}
                    onCancel={() => onClose(false)}
                    mode={mode}
                  />
                </Grid>
              </ConditionalComponent>
            </Grid>
          </form>
        </Box>
        <Grid item xs={12}>
          <ConditionalComponent isValid={formik.values.collaborators?.length > 0}>
            <Box sx={{ mt: 4, borderRadius: '10px' }}>
              <EquipeAgentsTable
                agentIds={formik.values.collaborators?.map((collaborator: any) => String(collaborator.id)) || []}
                isReadOnly={isReadOnly}
                onRemoveAgent={!isReadOnly ? handleRemoveAgent : undefined}
              />
            </Box>
          </ConditionalComponent>
        </Grid>
      </ScrollBox>
    </LocalizationProvider>
  );
}