/**
 * @ai-summary Form component for creating maintenance records with receipt OCR integration
 * @ai-context Mobile-first responsive design with tier-gated receipt scanning, mirrors FuelLogForm OCR pattern
 */

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,
  Dialog,
  Backdrop,
} 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 { useMaintenanceReceiptOcr } from '../hooks/useMaintenanceReceiptOcr';
import { MaintenanceReceiptReviewModal } from './MaintenanceReceiptReviewModal';
import { AddReceiptDialog } from './AddReceiptDialog';
import { CameraCapture } from '../../../shared/components/CameraCapture';
import { useTierAccess } from '../../../core/hooks/useTierAccess';
import { UpgradeRequiredDialog } from '../../../shared-minimal/components/UpgradeRequiredDialog';
import { documentsApi } from '../../documents/api/documents.api';
import toast from 'react-hot-toast';
import { getVehicleSubtitle } from '@/core/utils/vehicleDisplay';

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>;

interface MaintenanceRecordFormProps {
  vehicleId?: string;
  onSuccess?: () => void;
}

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

  // Tier access check for receipt scan feature
  const { hasAccess } = useTierAccess();
  const hasReceiptScanAccess = hasAccess('maintenance.receiptScan');
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false);

  // Receipt OCR integration
  const {
    isCapturing,
    isProcessing,
    result: ocrResult,
    receiptImageUrl,
    error: ocrError,
    startCapture,
    cancelCapture,
    processImage,
    acceptResult,
    reset: resetOcr,
    updateField,
  } = useMaintenanceReceiptOcr();

  // AddReceiptDialog visibility state
  const [showAddReceiptDialog, setShowAddReceiptDialog] = useState(false);

  // Store captured file for document upload on submit
  const [capturedReceiptFile, setCapturedReceiptFile] = useState<File | null>(null);

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

  // Sync vehicle_id when parent prop changes
  useEffect(() => {
    if (vehicleId) setValue('vehicle_id', vehicleId);
  }, [vehicleId, setValue]);

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

  // Wrap processImage to also save file reference
  const handleCaptureImage = async (file: File, croppedFile?: File) => {
    setCapturedReceiptFile(croppedFile || file);
    await processImage(file, croppedFile);
  };

  // Handle accepting OCR results and populating the form
  const handleAcceptOcrResult = () => {
    const mappedFields = acceptResult();
    if (!mappedFields) return;

    // Populate form fields from OCR result
    if (mappedFields.category) {
      setValue('category', mappedFields.category);
      setSelectedCategory(mappedFields.category);
    }
    if (mappedFields.subtypes && mappedFields.subtypes.length > 0) {
      setValue('subtypes', mappedFields.subtypes);
    }
    if (mappedFields.date) {
      setValue('date', mappedFields.date);
    }
    if (mappedFields.cost !== undefined) {
      setValue('cost', mappedFields.cost as any);
    }
    if (mappedFields.shopName) {
      setValue('shop_name', mappedFields.shopName);
    }
    if (mappedFields.odometerReading !== undefined) {
      setValue('odometer_reading', mappedFields.odometerReading as any);
    }
    if (mappedFields.notes) {
      setValue('notes', mappedFields.notes);
    }
  };

  // Handle retaking photo
  const handleRetakePhoto = () => {
    resetOcr();
    setCapturedReceiptFile(null);
    startCapture();
  };

  const onSubmit = async (data: FormData) => {
    try {
      let receiptDocumentId: string | undefined;

      // Upload receipt as document if we have a captured file
      if (capturedReceiptFile) {
        try {
          const doc = await documentsApi.create({
            vehicleId: data.vehicle_id,
            documentType: 'manual',
            title: `Maintenance Receipt - ${new Date(data.date).toLocaleDateString()}`,
          });
          await documentsApi.upload(doc.id, capturedReceiptFile);
          receiptDocumentId = doc.id;
        } catch (uploadError) {
          console.error('Failed to upload receipt document:', uploadError);
          toast.error('Receipt upload failed, but the record will be saved without the receipt.');
        }
      }

      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,
        receiptDocumentId,
      };

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

      // 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);
      setCapturedReceiptFile(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>
          {/* Add Receipt Button */}
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              mb: 3,
              pb: 2,
              borderBottom: '1px solid',
              borderColor: 'divider',
            }}
          >
            <Button
              variant="outlined"
              onClick={() => {
                if (!hasReceiptScanAccess) {
                  setShowUpgradeDialog(true);
                  return;
                }
                setShowAddReceiptDialog(true);
              }}
              disabled={isProcessing || isRecordMutating}
              sx={{
                minHeight: 44,
                borderStyle: 'dashed',
                borderWidth: 2,
                '&:hover': { borderWidth: 2 },
              }}
            >
              Add Receipt
            </Button>
          </Box>

          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={2}>
              {/* Vehicle Selection (hidden when vehicleId prop is provided) */}
              {!vehicleId && (
                <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}>
                                {getVehicleSubtitle(vehicle) || 'Unknown Vehicle'}
                              </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>

      {/* Add Receipt Dialog */}
      <AddReceiptDialog
        open={showAddReceiptDialog}
        onClose={() => setShowAddReceiptDialog(false)}
        onFileSelect={(file) => {
          setShowAddReceiptDialog(false);
          handleCaptureImage(file);
        }}
        onStartCamera={() => {
          setShowAddReceiptDialog(false);
          startCapture();
        }}
      />

      {/* Camera Capture Modal */}
      <Dialog
        open={isCapturing}
        onClose={cancelCapture}
        fullScreen
        PaperProps={{
          sx: { backgroundColor: 'black' },
        }}
      >
        <CameraCapture
          onCapture={handleCaptureImage}
          onCancel={cancelCapture}
          guidanceType="receipt"
          allowCrop={true}
        />
      </Dialog>

      {/* OCR Processing Overlay */}
      <Backdrop
        open={isProcessing}
        sx={{
          color: '#fff',
          zIndex: (theme) => theme.zIndex.drawer + 1,
          flexDirection: 'column',
          gap: 2,
        }}
      >
        <CircularProgress color="inherit" />
        <Typography variant="body1">Extracting receipt data...</Typography>
      </Backdrop>

      {/* OCR Review Modal */}
      {ocrResult && (
        <MaintenanceReceiptReviewModal
          open={!!ocrResult}
          extractedFields={ocrResult.extractedFields}
          receiptImageUrl={receiptImageUrl}
          categorySuggestion={ocrResult.categorySuggestion}
          onAccept={handleAcceptOcrResult}
          onRetake={handleRetakePhoto}
          onCancel={() => {
            resetOcr();
            setCapturedReceiptFile(null);
          }}
          onFieldEdit={updateField}
        />
      )}

      {/* Upgrade Required Dialog for Receipt Scan */}
      <UpgradeRequiredDialog
        featureKey="maintenance.receiptScan"
        open={showUpgradeDialog}
        onClose={() => setShowUpgradeDialog(false)}
      />

      {/* OCR Error Display */}
      {ocrError && (
        <Dialog open={!!ocrError} onClose={resetOcr} maxWidth="xs">
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography variant="h6" gutterBottom>
              OCR Error
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              {ocrError}
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
              <Button onClick={startCapture} variant="contained">
                Try Again
              </Button>
              <Button
                onClick={() => {
                  resetOcr();
                  setCapturedReceiptFile(null);
                }}
                variant="outlined"
              >
                Cancel
              </Button>
            </Box>
          </Box>
        </Dialog>
      )}
    </LocalizationProvider>
  );
};
