'use client';

import React, { useEffect, useState } from 'react';
import {
  Box,
  Stepper,
  Step,
  StepLabel,
  Grid,
  Divider,
} 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 { useFormik } from 'formik';
import { ConnectionSession, IAgent } from '@/shared/types/agent';
import { ScrollBox } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { ModeType } from '@/shared/types/common';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import {
  personalInfoFields,
  professionalInfoFields,
  rolePermissionFields,
} from '../utils/form-fields-agent';
import { agentSchema } from '../utils/agent-schema';
import ConnectionHistoryTable from '../components/connection-history-table';

const steps = [
  'Informations personnelles',
  'Informations professionnelles',
  'Rôles & permissions',
];

interface AgentFormProps {
  agent: IAgent;
  mode: ModeType;
  onSave: (updatedAgent: IAgent) => void;
  onEdit: (agent: IAgent) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, newContent: IAgent) => void
  tabId: string
}

export default function AgentForm({
  agent,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: AgentFormProps) {
  const [activeStep, setActiveStep] = useState(0);
  const isReadOnly = mode === 'view';

  const formik = useFormik<IAgent>({
    initialValues: agent,
    validationSchema: agentSchema,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
  });

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const handleNext = async () => {
    const fields = activeStep === 0 
      ? personalInfoFields 
      : activeStep === 1 
        ? professionalInfoFields 
        : rolePermissionFields;

    const fieldNames = fields.map(field => field.name);
    const errors = await formik.validateForm();
    const hasErrors = fieldNames.some(fieldName => errors[fieldName]);

    if (!hasErrors) {
      setActiveStep((prevStep) => prevStep + 1);
    } else {
      formik.setTouched(
        fieldNames.reduce((acc, fieldName) => ({
          ...acc,
          [fieldName]: true
        }), {})
      );
    }
  };

  const handleBack = () => {
    setActiveStep((prevStep) => prevStep - 1);
  };

  const renderStepContent = (step: number) => {
    const fields = step === 0 
      ? personalInfoFields 
      : step === 1 
        ? professionalInfoFields 
        : rolePermissionFields;

    return (
      <Grid container spacing={3}>
        {fields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            <FormField
              field={field}
              value={formik.values[field.name as keyof IAgent]}
              onChange={(name, value) => formik.setFieldValue(name, value)}
              error={
                formik.touched[field.name as keyof IAgent]
                  ?  field.name==="address" ? formik.errors.address?.["address"]
                  : formik.errors[field.name as keyof IAgent] as string 
                  : undefined
              }
              onBlur={formik.handleBlur}
              isReadOnly={ field.name === "permissions" || isReadOnly}
            />
          </Grid>
        ))}
      </Grid>
    );
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <ScrollBox>
        <Box sx={{ p: 3, backgroundColor: 'background.paper', borderRadius: 1 }}>
          <ConditionalComponent isValid={isReadOnly}>
            <EditExportButtons
              onEdit={() => onEdit(agent)}
              onExport={() => {}}
              tooltipTitle="l'agent"
            />
          </ConditionalComponent>

          <Box sx={{ mt: isReadOnly ? 3 : 0 }}>
            <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
              {steps.map((label) => (
                <Step key={label}>
                  <StepLabel>{label}</StepLabel>
                </Step>
              ))}
            </Stepper>

            <Box component="form" onSubmit={formik.handleSubmit}>
              {renderStepContent(activeStep)}

              <Box sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end' }}>
                <ConditionalComponent 
                  isValid={isReadOnly}
                  defaultComponent={
                    <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                      <ConditionalComponent 
                        isValid={activeStep === steps.length - 1}
                        defaultComponent={
                          <ActionButtons
                            onSave={formik.handleSubmit}
                            onNext={handleNext}
                            onBack={activeStep > 0 ? handleBack : undefined}
                            onCancel={() => onClose(false)}
                            mode={mode}
                          />
                        }
                      >
                        <ActionButtons
                          onSave={formik.handleSubmit}
                          onBack={handleBack}
                          onCancel={() => onClose(false)}
                          mode={mode}
                        />
                      </ConditionalComponent>
                    </Box>
                  }
                >
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <ConditionalComponent 
                      isValid={activeStep > 0}
                      defaultComponent={
                        <ActionButtons
                          onSave={formik.handleSubmit}
                          onNext={handleNext}
                          onCancel={() => onClose(false)}
                          mode="view"
                        />
                      }
                    >
                      <ActionButtons
                        onSave={formik.handleSubmit}
                        onBack={handleBack}
                        onNext={activeStep < steps.length - 1 ? handleNext : undefined}
                        onCancel={() => onClose(false)}
                        mode="view"
                      />
                    </ConditionalComponent>
                  </Box>
                </ConditionalComponent>
              </Box>
            </Box>
          </Box>
        </Box>
        <ConditionalComponent isValid={!!formik.values.connectionHistory && formik.values.connectionHistory.length > 0}>
          <>
            <Divider sx={{ my: 4 }} />
            <ConnectionHistoryTable connectionHistory={formik.values.connectionHistory} />
          </>
        </ConditionalComponent>
      </ScrollBox>
    </LocalizationProvider>
  );
}