'use client';

import React from 'react';
import {
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  Checkbox,
  FormGroup,
  Button,
  Box,
  FormHelperText,
  InputAdornment,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import { StyledTextField } from '@/shared/theme/css';
import { FormField } from '@/shared/api/endpoints/candidate-form';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import { styled } from '@mui/material/styles';

const VisuallyHiddenInput = styled('input')({
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  height: 1,
  overflow: 'hidden',
  position: 'absolute',
  bottom: 0,
  left: 0,
  whiteSpace: 'nowrap',
  width: 1,
});

interface CandidateFormFieldProps {
  field: FormField;
  value: any;
  onChange: (value: any) => void;
  error?: string;
  onFileUpload?: (file: File) => Promise<string>;
}

export default function CandidateFormField({
  field,
  value,
  onChange,
  error,
  onFileUpload,
}: CandidateFormFieldProps) {
  const [uploading, setUploading] = React.useState(false);

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file && onFileUpload) {
      setUploading(true);
      try {
        const fileUrl = await onFileUpload(file);
        onChange(fileUrl);
      } catch (error) {
        // Handle upload error silently
      } finally {
        setUploading(false);
      }
    }
  };

  const renderField = () => {
    switch (field.type) {
      case 'email':
        return (
          <StyledTextField
            fullWidth
            type="email"
            label={field.label}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
            required={field.isRequired}
            error={!!error}
            helperText={error || ' '}
            InputLabelProps={{ shrink: true }}
          />
        );

      case 'tel':
        return (
          <StyledTextField
            fullWidth
            type="tel"
            label={field.label}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
            required={field.isRequired}
            error={!!error}
            helperText={error || ' '}
            InputLabelProps={{ shrink: true }}
          />
        );

      case 'textarea':
        return (
          <StyledTextField
            fullWidth
            multiline
            rows={4}
            label={field.label}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
            required={field.isRequired}
            error={!!error}
            helperText={error || ' '}
            InputLabelProps={{ shrink: true }}
          />
        );

      case 'select':
        return (
          <FormControl fullWidth error={!!error}>
            <InputLabel 
              shrink 
              sx={{ 
                transform: "translate(14px, 4px) scale(0.8)",
                color: 'primary.main',
                '&.Mui-focused': { color: 'primary.main' }
              }}
            >
              {field.label}
              {field.isRequired && ' *'}
            </InputLabel>
            <Select
              value={value || ''}
              onChange={(e) => onChange(e.target.value)}
              required={field.isRequired}
              sx={{
                backgroundColor: (theme) => theme.palette.primary.main + '08',
                borderRadius: '12px',
                '& .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'primary.main',
                },
                '&:hover .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'primary.main',
                },
                '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'primary.main',
                  boxShadow: (theme) => `0 0 0 4px ${theme.palette.primary.main}20`,
                },
              }}
            >
              {field.options?.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
            <FormHelperText>{error || ' '}</FormHelperText>
          </FormControl>
        );

      case 'radio':
        return (
          <FormControl component="fieldset" fullWidth error={!!error}>
            <InputLabel 
              component="legend" 
              sx={{ 
                color: 'primary.main',
                fontSize: '0.8rem',
                fontWeight: 500,
                mb: 1,
                display: 'block'
              }}
            >
              {field.label}
              {field.isRequired && ' *'}
            </InputLabel>
            <RadioGroup
              value={value || ''}
              onChange={(e) => onChange(e.target.value)}
              sx={{ mt: 1 }}
            >
              {field.options?.map((option) => (
                <FormControlLabel
                  key={option.value}
                  value={option.value}
                  control={<Radio color="primary" />}
                  label={option.label}
                />
              ))}
            </RadioGroup>
            <FormHelperText>{error || ' '}</FormHelperText>
          </FormControl>
        );

      case 'checkbox':
        return (
          <FormControl component="fieldset" fullWidth error={!!error}>
            <InputLabel 
              component="legend" 
              sx={{ 
                color: 'primary.main',
                fontSize: '0.8rem',
                fontWeight: 500,
                mb: 1,
                display: 'block'
              }}
            >
              {field.label}
              {field.isRequired && ' *'}
            </InputLabel>
            <FormGroup sx={{ mt: 1 }}>
              {field.options?.map((option) => (
                <FormControlLabel
                  key={option.value}
                  control={
                    <Checkbox
                      checked={(value || []).includes(option.value)}
                      onChange={(e) => {
                        const currentValues = value || [];
                        if (e.target.checked) {
                          onChange([...currentValues, option.value]);
                        } else {
                          onChange(currentValues.filter((v: string) => v !== option.value));
                        }
                      }}
                      color="primary"
                    />
                  }
                  label={option.label}
                />
              ))}
            </FormGroup>
            <FormHelperText>{error || ' '}</FormHelperText>
          </FormControl>
        );

      case 'date':
        return (
          <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
            <DatePicker
              label={field.label}
              value={value ? new Date(value) : null}
              onChange={(newValue) => onChange(newValue?.toISOString().split('T')[0])}
              slots={{
                textField: (params) => (
                  <StyledTextField
                    {...params}
                    fullWidth
                    required={field.isRequired}
                    error={!!error}
                    helperText={error || ' '}
                    InputLabelProps={{ shrink: true }}
                  />
                ),
              }}
            />
          </LocalizationProvider>
        );

      case 'file':
        return (
          <Box sx={{ width: '100%' }}>
            <InputLabel 
              sx={{ 
                color: 'primary.main',
                fontSize: '0.8rem',
                fontWeight: 500,
                mb: 1,
                display: 'block'
              }}
            >
              {field.label}
              {field.isRequired && ' *'}
            </InputLabel>
            <Button
              component="label"
              variant="outlined"
              startIcon={<CloudUploadIcon />}
              disabled={uploading}
              sx={{
                width: '100%',
                height: 56,
                borderColor: 'primary.main',
                color: 'primary.main',
                backgroundColor: (theme) => theme.palette.primary.main + '08',
                borderRadius: '12px',
                border: '1px solid',
                '&:hover': {
                  borderColor: 'primary.main',
                  backgroundColor: (theme) => theme.palette.primary.main + '12',
                },
              }}
            >
              {uploading ? 'Téléchargement...' : value ? 'Fichier téléchargé' : 'Choisir un fichier'}
              <VisuallyHiddenInput type="file" onChange={handleFileChange} />
            </Button>
            {value && (
              <Box sx={{ mt: 1, fontSize: '0.875rem', color: 'success.main' }}>
                ✓ Fichier téléchargé avec succès
              </Box>
            )}
            {error && (
              <FormHelperText error sx={{ mt: 1 }}>
                {error}
              </FormHelperText>
            )}
          </Box>
        );

      default:
        return (
          <StyledTextField
            fullWidth
            label={field.label}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
            required={field.isRequired}
            error={!!error}
            helperText={error || ' '}
            InputLabelProps={{ shrink: true }}
          />
        );
    }
  };

  return (
    <Box sx={{ mb: 3 }}>
      {renderField()}
    </Box>
  );
}
