/**
 * @ai-summary Form component for creating maintenance records
 * @ai-context Mobile-first responsive design with proper validation
 */

import React, { useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Card,
  CardHeader,
  CardContent,
  TextField,
  Select,
  MenuItem,
  Button,
  Box,
  Grid,
  FormControl,
  InputLabel,
  FormHelperText,
  CircularProgress,
  Typography,
  InputAdornment,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from 'dayjs';
import { useMaintenanceRecords } from '../hooks/useMaintenanceRecords';
import { useVehicles } from '../../vehicles/hooks/useVehicles';
import { SubtypeCheckboxGroup } from './SubtypeCheckboxGroup';
import {
  MaintenanceCategory,
  CreateMaintenanceRecordRequest,
  getCategoryDisplayName,
} from '../types/maintenance.types';
import toast from 'react-hot-toast';

const schema = z.object({
  vehicle_id: z.string().uuid({ message: 'Please select a vehicle' }),
  category: z.enum(['routine_maintenance', 'repair', 'performance_upgrade'], {
    errorMap: () => ({ message: 'Please select a category' }),
  }),
  subtypes: z.array(z.string()).min(1, { message: 'Please select at least one subtype' }),
  date: z.string().min(1, { message: 'Date is required' }),
  odometer_reading: z.coerce.number().positive().optional().or(z.literal('')),
  cost: z.coerce.number().positive().optional().or(z.literal('')),
  shop_name: z.string().max(200).optional(),
  notes: z.string().max(1000).optional(),
});

type FormData = z.infer<typeof schema>;

export const MaintenanceRecordForm: React.FC = () => {
  const { data: vehicles, isLoading: isLoadingVehicles } = useVehicles();
  const { createRecord, isRecordMutating } = useMaintenanceRecords();
  const [selectedCategory, setSelectedCategory] = useState<MaintenanceCategory | null>(null);

  const {
    control,
    handleSubmit,
    watch,
    setValue,
    reset,
    formState: { errors, isValid },
  } = useForm<FormData>({
    resolver: zodResolver(schema),
    mode: 'onChange',
    defaultValues: {
      vehicle_id: '',
      category: undefined as any,
      subtypes: [],
      date: new Date().toISOString().split('T')[0],
      odometer_reading: '' as any,
      cost: '' as any,
      shop_name: '',
      notes: '',
    },
  });

  // Watch category changes to reset subtypes
  const watchedCategory = watch('category');
  useEffect(() => {
    if (watchedCategory) {
      setSelectedCategory(watchedCategory as MaintenanceCategory);
      setValue('subtypes', []);
    }
  }, [watchedCategory, setValue]);

  const onSubmit = async (data: FormData) => {
    try {
      const payload: CreateMaintenanceRecordRequest = {
        vehicleId: data.vehicle_id,
        category: data.category as MaintenanceCategory,
        subtypes: data.subtypes,
        date: data.date,
        odometerReading: data.odometer_reading ? Number(data.odometer_reading) : undefined,
        cost: data.cost ? Number(data.cost) : undefined,
        shopName: data.shop_name || undefined,
        notes: data.notes || undefined,
      };

      await createRecord(payload);
      toast.success('Maintenance record added successfully');

      // Reset form
      reset({
        vehicle_id: '',
        category: undefined as any,
        subtypes: [],
        date: new Date().toISOString().split('T')[0],
        odometer_reading: '' as any,
        cost: '' as any,
        shop_name: '',
        notes: '',
      });
      setSelectedCategory(null);
    } catch (error) {
      console.error('Failed to create maintenance record:', error);
      toast.error('Failed to add maintenance record');
    }
  };

  if (isLoadingVehicles) {
    return (
      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
            <CircularProgress />
          </Box>
        </CardContent>
      </Card>
    );
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Card>
        <CardHeader title="Add Maintenance Record" />
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={2}>
              {/* Vehicle Selection */}
              <Grid item xs={12}>
                <Controller
                  name="vehicle_id"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth error={!!errors.vehicle_id}>
                      <InputLabel id="vehicle-select-label">Vehicle *</InputLabel>
                      <Select
                        {...field}
                        labelId="vehicle-select-label"
                        label="Vehicle *"
                        sx={{ minHeight: 56 }}
                      >
                        {vehicles && vehicles.length > 0 ? (
                          vehicles.map((vehicle) => (
                            <MenuItem key={vehicle.id} value={vehicle.id}>
                              {vehicle.year} {vehicle.make} {vehicle.model}
                            </MenuItem>
                          ))
                        ) : (
                          <MenuItem disabled>No vehicles available</MenuItem>
                        )}
                      </Select>
                      {errors.vehicle_id && (
                        <FormHelperText>{errors.vehicle_id.message}</FormHelperText>
                      )}
                    </FormControl>
                  )}
                />
              </Grid>

              {/* Category Selection */}
              <Grid item xs={12}>
                <Controller
                  name="category"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth error={!!errors.category}>
                      <InputLabel id="category-select-label">Category *</InputLabel>
                      <Select
                        {...field}
                        labelId="category-select-label"
                        label="Category *"
                        sx={{ minHeight: 56 }}
                      >
                        <MenuItem value="routine_maintenance">
                          {getCategoryDisplayName('routine_maintenance')}
                        </MenuItem>
                        <MenuItem value="repair">{getCategoryDisplayName('repair')}</MenuItem>
                        <MenuItem value="performance_upgrade">
                          {getCategoryDisplayName('performance_upgrade')}
                        </MenuItem>
                      </Select>
                      {errors.category && (
                        <FormHelperText>{errors.category.message}</FormHelperText>
                      )}
                    </FormControl>
                  )}
                />
              </Grid>

              {/* Subtypes */}
              {selectedCategory && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom sx={{ mb: 1 }}>
                    Subtypes *
                  </Typography>
                  <Controller
                    name="subtypes"
                    control={control}
                    render={({ field }) => (
                      <Box>
                        <SubtypeCheckboxGroup
                          category={selectedCategory}
                          selected={field.value}
                          onChange={field.onChange}
                        />
                        {errors.subtypes && (
                          <FormHelperText error sx={{ mt: 1 }}>
                            {errors.subtypes.message}
                          </FormHelperText>
                        )}
                      </Box>
                    )}
                  />
                </Grid>
              )}

              {/* Date */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name="date"
                  control={control}
                  render={({ field }) => (
                    <DatePicker
                      label="Date *"
                      value={field.value ? dayjs(field.value) : null}
                      onChange={(newValue) =>
                        field.onChange(newValue?.toISOString().split('T')[0] || '')
                      }
                      format="MM/DD/YYYY"
                      slotProps={{
                        textField: {
                          fullWidth: true,
                          error: !!errors.date,
                          helperText: errors.date?.message,
                          sx: {
                            '& .MuiOutlinedInput-root': {
                              minHeight: 56,
                            },
                          },
                        },
                      }}
                    />
                  )}
                />
              </Grid>

              {/* Odometer Reading */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name="odometer_reading"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Odometer Reading"
                      type="number"
                      inputProps={{ step: 1, min: 0 }}
                      fullWidth
                      error={!!errors.odometer_reading}
                      helperText={errors.odometer_reading?.message}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          minHeight: 56,
                        },
                      }}
                    />
                  )}
                />
              </Grid>

              {/* Cost */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name="cost"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Cost"
                      type="number"
                      inputProps={{ step: 0.01, min: 0 }}
                      InputProps={{
                        startAdornment: <InputAdornment position="start">$</InputAdornment>,
                      }}
                      fullWidth
                      error={!!errors.cost}
                      helperText={errors.cost?.message}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          minHeight: 56,
                        },
                      }}
                    />
                  )}
                />
              </Grid>

              {/* Shop Name */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name="shop_name"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Shop Name"
                      fullWidth
                      error={!!errors.shop_name}
                      helperText={errors.shop_name?.message}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          minHeight: 56,
                        },
                      }}
                    />
                  )}
                />
              </Grid>

              {/* Notes */}
              <Grid item xs={12}>
                <Controller
                  name="notes"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Notes"
                      multiline
                      rows={3}
                      fullWidth
                      error={!!errors.notes}
                      helperText={errors.notes?.message}
                    />
                  )}
                />
              </Grid>

              {/* Submit Button */}
              <Grid item xs={12}>
                <Box display="flex" gap={2} justifyContent="flex-end">
                  <Button
                    type="submit"
                    variant="contained"
                    disabled={!isValid || isRecordMutating}
                    startIcon={isRecordMutating ? <CircularProgress size={18} /> : undefined}
                    sx={{
                      minHeight: 44,
                      minWidth: { xs: '100%', sm: 200 },
                    }}
                  >
                    Add Record
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </LocalizationProvider>
  );
};
