import React from 'react';
import { Box } from '@mui/material';
import { StyledDatePicker, StyledDateTimePicker } from '@/shared/theme/css';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import { FormFieldType } from '@/shared/types/common';
import { ICandidature } from '@/shared/types/candidature';
import { useResponsive } from '@/hooks';
import dayjs from 'dayjs';

interface CandidatureDateFieldProps {
  field: FormFieldType<ICandidature>;
  value: any;
  onChange: (name: string, value: any) => void;
  isReadOnly: boolean;
  error?: string;
  onBlur?: (e: React.FocusEvent) => void;
  isDrawerElement?: boolean;
}

function resolveRequired(
  required: boolean | ((values: any) => boolean) | undefined,
  formData?: any
): boolean {
  if (typeof required === 'function' && formData) {
    return required(formData);
  }
  return !!required;
}

export default function CandidatureDateField({
  field,
  value,
  onChange,
  isReadOnly,
  error,
  onBlur,
  isDrawerElement,
}: CandidatureDateFieldProps) {
  const isBetweenSmAndLg = useResponsive('between', 'sm', 'lg');
  const isSmallScreen = isBetweenSmAndLg || isDrawerElement;
  const isRequired = resolveRequired(field.required);

  // Convert the value to a proper dayjs object, handling empty strings
  const dateValue = (() => {
    if (!value || value === '') {
      return null;
    }
    try {
      const parsed = dayjs(value);
      return parsed.isValid() ? parsed : null;
    } catch (error) {
      console.warn('Invalid date value in CandidatureDateField:', value);
      return null;
    }
  })();

  // Determine if this is a datetime field
  const isDateTime = field.type === 'datetime';
  const PickerComponent = isDateTime ? StyledDateTimePicker : StyledDatePicker;

  return (
    <Box sx={{ width: '100%' }}>
      <PickerComponent
        isSmallScreen={isSmallScreen}
        label={
          <>
            {field.label}
            {isRequired ? <span style={{ color: '#FF0000' }}> *</span> : <></>}
          </>
        }
        views={['year', 'month', 'day']}
        slots={{
          openPickerIcon: () => <CustomDateIcon isReadOnly={isReadOnly} />,
        }}
        openTo="year"
        readOnly={isReadOnly}
        value={dateValue}
        {...(isDateTime && {
          ampm: false,
          format: 'DD/MM/YYYY HH:mm'
        })}
        onChange={(newDate) => {
          if (newDate && dayjs.isDayjs(newDate) && newDate.isValid() && newDate.year() >= 1800) {
            const dateString = isDateTime 
              ? newDate.format('YYYY-MM-DDTHH:mm:ss')
              : newDate.startOf('day').format('YYYY-MM-DDTHH:mm:ss');
            onChange(field.name, dateString);
          } else if (newDate === null) {
            onChange(field.name, '');
          }
        }}
        onError={(reason, value) => {
          console.warn('Date validation error:', {
            reason,
            value,
            field: field.name,
          });
        }}
        slotProps={{
          textField: (params) => ({
            ...params,
            fullWidth: true,
            placeholder: 'DD/MM/YYYY',
            InputLabelProps: {
              shrink: true,
            },
            error: !!error,
            helperText: error,
            onBlur: (e) => {
              if (onBlur) onBlur(e);
            },
          }),
          actionBar: {
            actions: ['clear', 'today'],
          },
        }}
        sx={{
          ...(!!error && {
            '& .MuiOutlinedInput-root': {
              borderColor: 'error.main',
            },
          }),
        }}
      />
    </Box>
  );
}
