import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { validateSubmissionHandler } from '@/lib/entityFormValidation';
import { getErrorMessage } from '@/lib/errorHandler';
import type { RideTechnicalSpec, RideCoasterStat, RideNameHistory } from '@/types/database';
import type { TempCompanyData, TempRideModelData, TempParkData } from '@/types/company';
import { entitySchemas, validateRequiredFields } from '@/lib/entityValidationSchemas';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { EntityMultiImageUploader, ImageAssignments } from '@/components/upload/EntityMultiImageUploader';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePicker } from '@/components/ui/date-picker';
import { FlexibleDateInput, type DatePrecision } from '@/components/ui/flexible-date-input';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Combobox } from '@/components/ui/combobox';
import { SlugField } from '@/components/ui/slug-field';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from '@/hooks/use-toast';
import { handleError } from '@/lib/errorHandler';
import { Plus, Zap, Save, X, Building2, AlertCircle } from 'lucide-react';
import { toDateOnly, parseDateOnly, toDateWithPrecision } from '@/lib/dateUtils';
import { useUnitPreferences } from '@/hooks/useUnitPreferences';
import { useManufacturers, useRideModels, useParks } from '@/hooks/useAutocompleteData';
import { useUserRole } from '@/hooks/useUserRole';
import { ManufacturerForm } from './ManufacturerForm';
import { RideModelForm } from './RideModelForm';
import { ParkForm } from './ParkForm';
import { TechnicalSpecsEditor, validateTechnicalSpecs } from './editors/TechnicalSpecsEditor';
import { CoasterStatsEditor, validateCoasterStats } from './editors/CoasterStatsEditor';
import { FormerNamesEditor } from './editors/FormerNamesEditor';
import { 
  convertValueToMetric,
  convertValueFromMetric,
  getDisplayUnit,
  getSpeedUnit,
  getDistanceUnit,
  getHeightUnit
} from '@/lib/units';

type RideFormData = z.infer<typeof entitySchemas.ride>;

interface RideFormProps {
  onSubmit: (data: RideFormData & {
    _tempNewPark?: TempParkData;
    _tempNewManufacturer?: TempCompanyData;
    _tempNewDesigner?: TempCompanyData;
    _tempNewRideModel?: TempRideModelData;
  }) => Promise<void>;
  onCancel?: () => void;
  initialData?: Partial<RideFormData & {
    id?: string;
    banner_image_url?: string;
    card_image_url?: string;
    _tempNewPark?: TempParkData;
    _tempNewManufacturer?: TempCompanyData;
    _tempNewDesigner?: TempCompanyData;
    _tempNewRideModel?: TempRideModelData;
  }>;
  isEditing?: boolean;
}

const categories = [
  'roller_coaster',
  'flat_ride',
  'water_ride',
  'dark_ride',
  'kiddie_ride',
  'transportation'
];

const statusOptions = [
  'Operating',
  'Closed Temporarily',
  'Closed Permanently',
  'Under Construction',
  'Relocated',
  'Stored',
  'Demolished'
];

const coasterTypes = [
  'steel',
  'wood',
  'hybrid'
];

const seatingTypes = [
  'sit_down',
  'stand_up',
  'flying',
  'inverted',
  'floorless',
  'suspended',
  'wing',
  'dive',
  'spinning'
];

const intensityLevels = [
  'family',
  'thrill',
  'extreme'
];

const TRACK_MATERIALS = [
  { value: 'steel', label: 'Steel' },
  { value: 'wood', label: 'Wood' },
];

const SUPPORT_MATERIALS = [
  { value: 'steel', label: 'Steel' },
  { value: 'wood', label: 'Wood' },
];

const PROPULSION_METHODS = [
  { value: 'chain_lift', label: 'Chain Lift' },
  { value: 'cable_lift', label: 'Cable Lift' },
  { value: 'friction_wheel_lift', label: 'Friction Wheel Lift' },
  { value: 'lsm_launch', label: 'LSM Launch' },
  { value: 'lim_launch', label: 'LIM Launch' },
  { value: 'hydraulic_launch', label: 'Hydraulic Launch' },
  { value: 'compressed_air_launch', label: 'Compressed Air Launch' },
  { value: 'flywheel_launch', label: 'Flywheel Launch' },
  { value: 'gravity', label: 'Gravity' },
  { value: 'tire_drive', label: 'Tire Drive' },
  { value: 'water_propulsion', label: 'Water Propulsion' },
  { value: 'other', label: 'Other' },
];

// Status value mappings between display (form) and database values
const STATUS_DISPLAY_TO_DB: Record<string, string> = {
  'Operating': 'operating',
  'Closed Temporarily': 'closed_temporarily',
  'Closed Permanently': 'closed_permanently',
  'Under Construction': 'under_construction',
  'Relocated': 'relocated',
  'Stored': 'stored',
  'Demolished': 'demolished'
};

const STATUS_DB_TO_DISPLAY: Record<string, string> = {
  'operating': 'Operating',
  'closed_permanently': 'Closed Permanently',
  'closed_temporarily': 'Closed Temporarily',
  'under_construction': 'Under Construction',
  'relocated': 'Relocated',
  'stored': 'Stored',
  'demolished': 'Demolished'
};

export function RideForm({ onSubmit, onCancel, initialData, isEditing = false }: RideFormProps) {
  const { isModerator } = useUserRole();
  const { preferences } = useUnitPreferences();
  const measurementSystem = preferences.measurement_system;
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Validate that onSubmit uses submission helpers (dev mode only)
  useEffect(() => {
    validateSubmissionHandler(onSubmit, 'ride');
  }, [onSubmit]);

  // Temp entity states
  const [tempNewPark, setTempNewPark] = useState<TempParkData | null>(initialData?._tempNewPark || null);
  const [selectedManufacturerId, setSelectedManufacturerId] = useState<string>(
    initialData?.manufacturer_id || ''
  );
  const [selectedManufacturerName, setSelectedManufacturerName] = useState<string>('');
  const [tempNewManufacturer, setTempNewManufacturer] = useState<TempCompanyData | null>(initialData?._tempNewManufacturer || null);
  const [tempNewDesigner, setTempNewDesigner] = useState<TempCompanyData | null>(initialData?._tempNewDesigner || null);
  const [tempNewRideModel, setTempNewRideModel] = useState<TempRideModelData | null>(initialData?._tempNewRideModel || null);
  const [isParkModalOpen, setIsParkModalOpen] = useState(false);
  const [isManufacturerModalOpen, setIsManufacturerModalOpen] = useState(false);
  const [isDesignerModalOpen, setIsDesignerModalOpen] = useState(false);
  const [isModelModalOpen, setIsModelModalOpen] = useState(false);

  // Advanced editor state - using simplified interface for editors (DB fields added on submit)
  const [technicalSpecs, setTechnicalSpecs] = useState<{
    spec_name: string;
    spec_value: string;
    spec_type: 'string' | 'number' | 'boolean' | 'date';
    category?: string;
    unit?: string;
    display_order: number;
  }[]>([]);
  const [coasterStats, setCoasterStats] = useState<{
    stat_name: string;
    stat_value: number;
    unit?: string;
    category?: string;
    description?: string;
    display_order: number;
  }[]>([]);
  const [formerNames, setFormerNames] = useState<{
    former_name: string;
    date_changed?: Date | null;
    reason?: string;
    from_year?: number;
    to_year?: number;
    order_index: number;
  }[]>([]);

  // Fetch data
  const { manufacturers, loading: manufacturersLoading } = useManufacturers();
  const { rideModels, loading: modelsLoading } = useRideModels(selectedManufacturerId);
  const { parks, loading: parksLoading } = useParks();

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    trigger,
    formState: { errors }
  } = useForm<RideFormData>({
    resolver: zodResolver(entitySchemas.ride),
    defaultValues: {
      name: initialData?.name || '',
      slug: initialData?.slug || '',
      description: initialData?.description || '',
      category: initialData?.category || '',
      ride_sub_type: initialData?.ride_sub_type || '',
      status: initialData?.status || 'operating' as const, // Store DB value directly
      opening_date: initialData?.opening_date || undefined,
      opening_date_precision: initialData?.opening_date_precision || 'day',
      closing_date: initialData?.closing_date || undefined,
      closing_date_precision: initialData?.closing_date_precision || 'day',
      // Convert metric values to user's preferred unit for display
      height_requirement: initialData?.height_requirement 
        ? convertValueFromMetric(initialData.height_requirement, getDisplayUnit('cm', measurementSystem), 'cm') 
        : undefined,
      age_requirement: initialData?.age_requirement || undefined,
      capacity_per_hour: initialData?.capacity_per_hour || undefined,
      duration_seconds: initialData?.duration_seconds || undefined,
      max_speed_kmh: initialData?.max_speed_kmh 
        ? convertValueFromMetric(initialData.max_speed_kmh, getDisplayUnit('km/h', measurementSystem), 'km/h') 
        : undefined,
      max_height_meters: initialData?.max_height_meters 
        ? convertValueFromMetric(initialData.max_height_meters, getDisplayUnit('m', measurementSystem), 'm') 
        : undefined,
      length_meters: initialData?.length_meters 
        ? convertValueFromMetric(initialData.length_meters, getDisplayUnit('m', measurementSystem), 'm') 
        : undefined,
      inversions: initialData?.inversions || undefined,
      coaster_type: initialData?.coaster_type || undefined,
      seating_type: initialData?.seating_type || undefined,
      intensity_level: initialData?.intensity_level || undefined,
      drop_height_meters: initialData?.drop_height_meters 
        ? convertValueFromMetric(initialData.drop_height_meters, getDisplayUnit('m', measurementSystem), 'm') 
        : undefined,
      max_g_force: initialData?.max_g_force || undefined,
      manufacturer_id: initialData?.manufacturer_id || undefined,
      ride_model_id: initialData?.ride_model_id || undefined,
      source_url: initialData?.source_url || '',
      submission_notes: initialData?.submission_notes || '',
      images: { uploaded: [] },
      park_id: initialData?.park_id || undefined
    }
  });

  const selectedCategory = watch('category');
  const isParkPreselected = !!initialData?.park_id; // Coming from park detail page


  const handleFormSubmit = async (data: RideFormData) => {
    setIsSubmitting(true);
    try {
      // Pre-submission validation for required fields
      const { valid, errors: validationErrors } = validateRequiredFields('ride', data);
      if (!valid) {
        validationErrors.forEach(error => {
          toast({
            variant: 'destructive',
            title: 'Missing Required Fields',
            description: error
          });
        });
        setIsSubmitting(false);
        return;
      }

      // CRITICAL: Block new photo uploads on edits
      if (isEditing && data.images?.uploaded) {
        const hasNewPhotos = data.images.uploaded.some(img => img.isLocal);
        if (hasNewPhotos) {
          toast({
            variant: 'destructive',
            title: 'Validation Error',
            description: 'New photos cannot be added during edits. Please remove new photos or use the photo gallery.'
          });
          return;
        }
      }

      // Validate coaster stats
      if (coasterStats && coasterStats.length > 0) {
        const statsValidation = validateCoasterStats(coasterStats);
        if (!statsValidation.valid) {
          toast({
            title: 'Invalid coaster statistics',
            description: statsValidation.errors.join(', '),
            variant: 'destructive'
          });
          return;
        }
      }
      
      // Validate technical specs
      if (technicalSpecs && technicalSpecs.length > 0) {
        const specsValidation = validateTechnicalSpecs(technicalSpecs);
        if (!specsValidation.valid) {
          toast({
            title: 'Invalid technical specifications',
            description: specsValidation.errors.join(', '),
            variant: 'destructive'
          });
          return;
        }
      }
      
      // Convert form values back to metric for storage
      const metricData = {
        ...data,
        // Status is already in DB format
        height_requirement: data.height_requirement
          ? convertValueToMetric(data.height_requirement, getDisplayUnit('cm', measurementSystem)) 
          : undefined,
        max_speed_kmh: data.max_speed_kmh 
          ? convertValueToMetric(data.max_speed_kmh, getDisplayUnit('km/h', measurementSystem)) 
          : undefined,
        max_height_meters: data.max_height_meters 
          ? convertValueToMetric(data.max_height_meters, getDisplayUnit('m', measurementSystem)) 
          : undefined,
        length_meters: data.length_meters 
          ? convertValueToMetric(data.length_meters, getDisplayUnit('m', measurementSystem)) 
          : undefined,
        drop_height_meters: data.drop_height_meters 
          ? convertValueToMetric(data.drop_height_meters, getDisplayUnit('m', measurementSystem)) 
          : undefined,
        // Pass relational data for proper handling
        _technical_specifications: technicalSpecs,
        _coaster_statistics: coasterStats,
        _name_history: formerNames,
        _tempNewPark: tempNewPark || undefined,
        _tempNewManufacturer: tempNewManufacturer || undefined,
        _tempNewDesigner: tempNewDesigner || undefined,
        _tempNewRideModel: tempNewRideModel || undefined
      };

      // Pass clean data to parent with extended fields
      await onSubmit(metricData);
      
      toast({
        title: isEditing ? "Ride Updated" : "Submission Sent",
        description: isEditing 
          ? "The ride information has been updated successfully."
          : tempNewManufacturer 
            ? "Ride, manufacturer, and model submitted for review"
            : "Ride submitted for review"
      });
    } catch (error: unknown) {
      handleError(error, {
        action: isEditing ? 'Update Ride' : 'Create Ride',
        metadata: { 
          rideName: data.name,
          hasNewManufacturer: !!tempNewManufacturer,
          hasNewModel: !!tempNewRideModel
        }
      });
      
      // Re-throw so parent can handle modal closing
      throw error;
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Zap className="w-5 h-5" />
          {isEditing ? 'Edit Ride' : 'Create New Ride'}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
          {/* Basic Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="name">Ride Name *</Label>
              <Input
                id="name"
                {...register('name')}
                placeholder="Enter ride name"
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message}</p>
              )}
            </div>

            <SlugField
              name={watch('name')}
              slug={watch('slug')}
              onSlugChange={(slug) => setValue('slug', slug)}
              isModerator={isModerator()}
            />
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              {...register('description')}
              placeholder="Describe the ride experience..."
              rows={4}
            />
          </div>

          {/* Park Selection */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Park Information</h3>
            
            <div className="space-y-2">
              <Label className="flex items-center gap-1">
                Park
                <span className="text-destructive">*</span>
              </Label>
              
              {tempNewPark ? (
                // Show temp park badge
                <div className="flex items-center gap-2 p-3 border rounded-md bg-green-50 dark:bg-green-950">
                  <Badge variant="secondary">New</Badge>
                  <span className="font-medium">{tempNewPark.name}</span>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setTempNewPark(null);
                    }}
                    disabled={isParkPreselected}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => setIsParkModalOpen(true)}
                    disabled={isParkPreselected}
                  >
                    Edit
                  </Button>
                </div>
              ) : (
                // Show combobox for existing parks
                <Combobox
                  options={parks}
                  value={watch('park_id') || undefined}
                  onValueChange={(value) => {
                    setValue('park_id', value);
                    trigger('park_id');
                  }}
                  placeholder={isParkPreselected ? "Park pre-selected" : "Select a park"}
                  searchPlaceholder="Search parks..."
                  emptyText="No parks found"
                  loading={parksLoading}
                  disabled={isParkPreselected}
                />
              )}
              
              {/* Validation error display */}
              {errors.park_id && (
                <p className="text-sm text-destructive flex items-center gap-1">
                  <AlertCircle className="w-4 h-4" />
                  {errors.park_id.message}
                </p>
              )}
              
              {/* Create New Park Button */}
              {!tempNewPark && !isParkPreselected && (
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="w-full"
                  onClick={() => setIsParkModalOpen(true)}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  Create New Park
                </Button>
              )}
              
              {/* Help text */}
              {isParkPreselected ? (
                <p className="text-sm text-muted-foreground">
                  Park is pre-selected from the park detail page and cannot be changed.
                </p>
              ) : (
                <p className="text-sm text-muted-foreground">
                  {tempNewPark 
                    ? "New park will be created when submission is approved"
                    : "Select the park where this ride is located"}
                </p>
              )}
            </div>
          </div>

          {/* Category and Status */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div className="space-y-2">
              <Label>Category *</Label>
              <Select onValueChange={(value) => setValue('category', value)} defaultValue={initialData?.category}>
                <SelectTrigger>
                  <SelectValue placeholder="Select category" />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((category) => (
                    <SelectItem key={category} value={category}>
                      {category.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.category && (
                <p className="text-sm text-destructive">{errors.category.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="ride_sub_type">Sub Type</Label>
              <Input
                id="ride_sub_type"
                {...register('ride_sub_type')}
                placeholder="e.g. Inverted Coaster, Log Flume"
              />
            </div>

            <div className="space-y-2">
              <Label>Status *</Label>
              <Select 
                onValueChange={(value) => setValue('status', value as "operating" | "closed_permanently" | "closed_temporarily" | "under_construction" | "relocated" | "stored" | "demolished")} 
                defaultValue={initialData?.status || 'operating'}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map((displayStatus) => {
                    const dbValue = STATUS_DISPLAY_TO_DB[displayStatus];
                    return (
                      <SelectItem key={dbValue} value={dbValue}>
                        {displayStatus}
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>
              {errors.status && (
                <p className="text-sm text-destructive">{errors.status.message}</p>
              )}
            </div>
          </div>

          {/* Manufacturer & Model Selection */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Manufacturer & Model</h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Manufacturer Column */}
              <div className="space-y-2">
                <Label>Manufacturer</Label>
                
                {tempNewManufacturer ? (
                  // Show temp manufacturer badge
                  <div className="flex items-center gap-2 p-3 border rounded-md bg-blue-50 dark:bg-blue-950">
                    <Badge variant="secondary">New</Badge>
                    <span className="font-medium">{tempNewManufacturer.name}</span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        setTempNewManufacturer(null);
                        setTempNewRideModel(null); // Clear model too
                      }}
                    >
                      <X className="w-4 h-4" />
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => setIsManufacturerModalOpen(true)}
                    >
                      Edit
                    </Button>
                  </div>
                ) : (
                  // Show combobox for existing manufacturers
                  <Combobox
                    options={manufacturers}
                    value={watch('manufacturer_id') || undefined}
                    onValueChange={(value) => {
                      setValue('manufacturer_id', value);
                      setSelectedManufacturerId(value);
                      // Find and set manufacturer name
                      const mfr = manufacturers.find(m => m.value === value);
                      setSelectedManufacturerName(mfr?.label || '');
                      // Clear model when manufacturer changes
                      setValue('ride_model_id', undefined);
                      setTempNewRideModel(null);
                    }}
                    placeholder="Select manufacturer"
                    searchPlaceholder="Search manufacturers..."
                    emptyText="No manufacturers found"
                    loading={manufacturersLoading}
                  />
                )}
                
                {/* Create New Manufacturer Button */}
                {!tempNewManufacturer && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="w-full"
                    onClick={() => setIsManufacturerModalOpen(true)}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    Create New Manufacturer
                  </Button>
                )}
              </div>

              {/* Ride Model Column - Conditional */}
              {(selectedManufacturerId || tempNewManufacturer) && (
                <div className="space-y-2">
                  <Label>Ride Model (Optional)</Label>
                  
                  {tempNewRideModel ? (
                    // Show temp model badge
                    <div className="flex items-center gap-2 p-3 border rounded-md bg-purple-50 dark:bg-purple-950">
                      <Badge variant="secondary">New</Badge>
                      <span className="font-medium">{tempNewRideModel.name}</span>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setTempNewRideModel(null)}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setIsModelModalOpen(true)}
                      >
                        Edit
                      </Button>
                    </div>
                  ) : (
                    // Show combobox for existing models
                    <>
                      <Combobox
                        options={rideModels}
                        value={watch('ride_model_id') || undefined}
                        onValueChange={(value) => setValue('ride_model_id', value)}
                        placeholder="Select model"
                        searchPlaceholder="Search models..."
                        emptyText={tempNewManufacturer 
                          ? "Create the manufacturer first to add models" 
                          : "No models found for this manufacturer"}
                        loading={modelsLoading}
                        disabled={!!tempNewManufacturer}
                      />
                      
                      {/* Create New Model Button */}
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="w-full"
                        onClick={() => setIsModelModalOpen(true)}
                      >
                        <Plus className="w-4 h-4 mr-2" />
                        Create New Model
                      </Button>
                    </>
                  )}
                  
                  <p className="text-xs text-muted-foreground">
                    {tempNewManufacturer 
                      ? "New models will be created after manufacturer approval"
                      : "Select a specific model or leave blank"}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Dates */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FlexibleDateInput
              value={watch('opening_date') ? parseDateOnly(watch('opening_date')!) : undefined}
              precision={(watch('opening_date_precision') as DatePrecision) || 'day'}
              onChange={(date, precision) => {
                setValue('opening_date', date ? toDateWithPrecision(date, precision) : undefined);
                setValue('opening_date_precision', precision);
              }}
              label="Opening Date"
              placeholder="Select opening date"
              disableFuture={true}
              fromYear={1800}
            />

            <FlexibleDateInput
              value={watch('closing_date') ? parseDateOnly(watch('closing_date')!) : undefined}
              precision={(watch('closing_date_precision') as DatePrecision) || 'day'}
              onChange={(date, precision) => {
                setValue('closing_date', date ? toDateWithPrecision(date, precision) : undefined);
                setValue('closing_date_precision', precision);
              }}
              label="Closing Date (if applicable)"
              placeholder="Select closing date"
              disablePast={false}
              fromYear={1800}
            />
          </div>

          {/* Requirements */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="height_requirement">Height Requirement ({getHeightUnit(measurementSystem)})</Label>
              <Input
                id="height_requirement"
                type="number"
                min="0"
                {...register('height_requirement', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                placeholder={measurementSystem === 'imperial' ? 'e.g. 47' : 'e.g. 120'}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="age_requirement">Minimum Age</Label>
              <Input
                id="age_requirement"
                type="number"
                min="0"
                {...register('age_requirement', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                placeholder="e.g. 8"
              />
            </div>
          </div>

          {/* Roller Coaster Specific Fields */}
          {selectedCategory === 'roller_coaster' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Roller Coaster Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label>Coaster Type</Label>
                  <Select onValueChange={(value) => setValue('coaster_type', value)} defaultValue={initialData?.coaster_type ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select type" />
                    </SelectTrigger>
                    <SelectContent>
                      {coasterTypes.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type.charAt(0).toUpperCase() + type.slice(1)}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>Seating Type</Label>
                  <Select onValueChange={(value) => setValue('seating_type', value)} defaultValue={initialData?.seating_type ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select seating" />
                    </SelectTrigger>
                    <SelectContent>
                      {seatingTypes.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>Intensity Level</Label>
                  <Select onValueChange={(value) => setValue('intensity_level', value)} defaultValue={initialData?.intensity_level ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select intensity" />
                    </SelectTrigger>
                    <SelectContent>
                      {intensityLevels.map((level) => (
                        <SelectItem key={level} value={level}>
                          {level.charAt(0).toUpperCase() + level.slice(1)}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-3">
                  <Label>Track Material(s)</Label>
                  <p className="text-sm text-muted-foreground">Select all materials used in the track</p>
                  <div className="grid grid-cols-2 gap-3">
                    {TRACK_MATERIALS.map((material) => (
                      <div key={material.value} className="flex items-center space-x-2">
                        <Checkbox
                          id={`track_${material.value}`}
                          checked={watch('track_material')?.includes(material.value) || false}
                          onCheckedChange={(checked) => {
                            const current = watch('track_material') || [];
                            if (checked) {
                              setValue('track_material', [...current, material.value]);
                            } else {
                              setValue('track_material', current.filter((v) => v !== material.value));
                            }
                          }}
                        />
                        <Label htmlFor={`track_${material.value}`} className="font-normal cursor-pointer">
                          {material.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="space-y-3">
                  <Label>Support Material(s)</Label>
                  <p className="text-sm text-muted-foreground">Select all materials used in the supports</p>
                  <div className="grid grid-cols-2 gap-3">
                    {SUPPORT_MATERIALS.map((material) => (
                      <div key={material.value} className="flex items-center space-x-2">
                        <Checkbox
                          id={`support_${material.value}`}
                          checked={watch('support_material')?.includes(material.value) || false}
                          onCheckedChange={(checked) => {
                            const current = watch('support_material') || [];
                            if (checked) {
                              setValue('support_material', [...current, material.value]);
                            } else {
                              setValue('support_material', current.filter((v) => v !== material.value));
                            }
                          }}
                        />
                        <Label htmlFor={`support_${material.value}`} className="font-normal cursor-pointer">
                          {material.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="space-y-3">
                  <Label>Propulsion Method(s)</Label>
                  <p className="text-sm text-muted-foreground">Select all propulsion methods used</p>
                  <div className="grid grid-cols-2 gap-3">
                    {PROPULSION_METHODS.map((method) => (
                      <div key={method.value} className="flex items-center space-x-2">
                        <Checkbox
                          id={`propulsion_${method.value}`}
                          checked={watch('propulsion_method')?.includes(method.value) || false}
                          onCheckedChange={(checked) => {
                            const current = watch('propulsion_method') || [];
                            if (checked) {
                              setValue('propulsion_method', [...current, method.value]);
                            } else {
                              setValue('propulsion_method', current.filter((v) => v !== method.value));
                            }
                          }}
                        />
                        <Label htmlFor={`propulsion_${method.value}`} className="font-normal cursor-pointer">
                          {method.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="drop_height_meters">Drop Height ({getDistanceUnit(measurementSystem)})</Label>
                  <Input
                    id="drop_height_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('drop_height_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 149' : 'e.g. 45.5'}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="max_g_force">Max G-Force</Label>
                  <Input
                    id="max_g_force"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('max_g_force', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder="e.g. 4.2"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Water Ride Specific Fields */}
          {selectedCategory === 'water_ride' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Water Ride Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="water_depth_cm">Water Depth ({getHeightUnit(measurementSystem)})</Label>
                  <Input
                    id="water_depth_cm"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('water_depth_cm', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 47' : 'e.g. 120'}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="splash_height_meters">Splash Height ({getDistanceUnit(measurementSystem)})</Label>
                  <Input
                    id="splash_height_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('splash_height_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 16' : 'e.g. 5'}
                  />
                </div>

                <div className="space-y-2">
                  <Label>Wetness Level</Label>
                  <Select onValueChange={(value) => setValue('wetness_level', value as 'dry' | 'light' | 'moderate' | 'soaked')} defaultValue={initialData?.wetness_level ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select wetness level" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="dry">Dry</SelectItem>
                      <SelectItem value="light">Light</SelectItem>
                      <SelectItem value="moderate">Moderate</SelectItem>
                      <SelectItem value="soaked">Soaked</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="flume_type">Flume Type</Label>
                  <Input
                    id="flume_type"
                    {...register('flume_type')}
                    placeholder="e.g. Log Flume, Shoot the Chute"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="boat_capacity">Boat Capacity</Label>
                  <Input
                    id="boat_capacity"
                    type="number"
                    min="1"
                    {...register('boat_capacity', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 8"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Dark Ride Specific Fields */}
          {selectedCategory === 'dark_ride' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Dark Ride Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="theme_name">Theme Name</Label>
                  <Input
                    id="theme_name"
                    {...register('theme_name')}
                    placeholder="e.g. Haunted Mansion, Pirates"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="show_duration_seconds">Show Duration (seconds)</Label>
                  <Input
                    id="show_duration_seconds"
                    type="number"
                    min="0"
                    {...register('show_duration_seconds', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 420"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="animatronics_count">Animatronics Count</Label>
                  <Input
                    id="animatronics_count"
                    type="number"
                    min="0"
                    {...register('animatronics_count', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 15"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="projection_type">Projection Type</Label>
                  <Input
                    id="projection_type"
                    {...register('projection_type')}
                    placeholder="e.g. 3D, 4D, LED, Projection Mapping"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="ride_system">Ride System</Label>
                  <Input
                    id="ride_system"
                    {...register('ride_system')}
                    placeholder="e.g. Omnimover, Dark Coaster, Trackless"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="scenes_count">Number of Scenes</Label>
                  <Input
                    id="scenes_count"
                    type="number"
                    min="0"
                    {...register('scenes_count', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 12"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="story_description">Story Description</Label>
                <Textarea
                  id="story_description"
                  {...register('story_description')}
                  placeholder="Describe the storyline and narrative..."
                  rows={3}
                />
              </div>
            </div>
          )}

          {/* Flat Ride Specific Fields */}
          {selectedCategory === 'flat_ride' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Flat Ride Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label>Rotation Type</Label>
                  <Select onValueChange={(value) => setValue('rotation_type', value as 'horizontal' | 'vertical' | 'multi_axis' | 'pendulum' | 'none')} defaultValue={initialData?.rotation_type ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select rotation type" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="horizontal">Horizontal</SelectItem>
                      <SelectItem value="vertical">Vertical</SelectItem>
                      <SelectItem value="multi_axis">Multi-Axis</SelectItem>
                      <SelectItem value="pendulum">Pendulum</SelectItem>
                      <SelectItem value="none">None</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="platform_count">Platform/Gondola Count</Label>
                  <Input
                    id="platform_count"
                    type="number"
                    min="1"
                    {...register('platform_count', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 8"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="swing_angle_degrees">Swing Angle (degrees)</Label>
                  <Input
                    id="swing_angle_degrees"
                    type="number"
                    min="0"
                    max="360"
                    step="0.1"
                    {...register('swing_angle_degrees', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder="e.g. 120"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="rotation_speed_rpm">Rotation Speed (RPM)</Label>
                  <Input
                    id="rotation_speed_rpm"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('rotation_speed_rpm', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder="e.g. 12"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="arm_length_meters">Arm Length ({getDistanceUnit(measurementSystem)})</Label>
                  <Input
                    id="arm_length_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('arm_length_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 33' : 'e.g. 10'}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="max_height_reached_meters">Max Height Reached ({getDistanceUnit(measurementSystem)})</Label>
                  <Input
                    id="max_height_reached_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('max_height_reached_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 98' : 'e.g. 30'}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="motion_pattern">Motion Pattern</Label>
                <Input
                  id="motion_pattern"
                  {...register('motion_pattern')}
                  placeholder="e.g. Circular, Wave, Pendulum swing"
                />
              </div>
            </div>
          )}

          {/* Kiddie Ride Specific Fields */}
          {selectedCategory === 'kiddie_ride' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Kiddie Ride Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="min_age">Minimum Age</Label>
                  <Input
                    id="min_age"
                    type="number"
                    min="0"
                    max="18"
                    {...register('min_age', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 2"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="max_age">Maximum Age</Label>
                  <Input
                    id="max_age"
                    type="number"
                    min="0"
                    max="18"
                    {...register('max_age', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 12"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="educational_theme">Educational Theme</Label>
                  <Input
                    id="educational_theme"
                    {...register('educational_theme')}
                    placeholder="e.g. Learning colors, Numbers"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="character_theme">Character Theme</Label>
                  <Input
                    id="character_theme"
                    {...register('character_theme')}
                    placeholder="e.g. Mickey Mouse, Dinosaurs"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Transportation Ride Specific Fields */}
          {selectedCategory === 'transportation' && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">Transportation Ride Details</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label>Transport Type</Label>
                  <Select onValueChange={(value) => setValue('transport_type', value as 'train' | 'monorail' | 'skylift' | 'ferry' | 'peoplemover' | 'cable_car')} defaultValue={initialData?.transport_type ?? undefined}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select transport type" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="train">Train</SelectItem>
                      <SelectItem value="monorail">Monorail</SelectItem>
                      <SelectItem value="skylift">Skylift / Chairlift</SelectItem>
                      <SelectItem value="ferry">Ferry / Boat</SelectItem>
                      <SelectItem value="peoplemover">PeopleMover</SelectItem>
                      <SelectItem value="cable_car">Cable Car</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="route_length_meters">Route Length ({getDistanceUnit(measurementSystem)})</Label>
                  <Input
                    id="route_length_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('route_length_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                    placeholder={measurementSystem === 'imperial' ? 'e.g. 3280' : 'e.g. 1000'}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="stations_count">Number of Stations</Label>
                  <Input
                    id="stations_count"
                    type="number"
                    min="2"
                    {...register('stations_count', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 4"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="vehicle_capacity">Vehicle Capacity</Label>
                  <Input
                    id="vehicle_capacity"
                    type="number"
                    min="1"
                    {...register('vehicle_capacity', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 40"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="vehicles_count">Number of Vehicles</Label>
                  <Input
                    id="vehicles_count"
                    type="number"
                    min="1"
                    {...register('vehicles_count', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 6"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="round_trip_duration_seconds">Round Trip Duration (seconds)</Label>
                  <Input
                    id="round_trip_duration_seconds"
                    type="number"
                    min="0"
                    {...register('round_trip_duration_seconds', { setValueAs: (v) => v === "" ? undefined : parseInt(v) })}
                    placeholder="e.g. 600"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Technical Specifications */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Technical Specifications</h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label htmlFor="capacity_per_hour">Capacity per Hour</Label>
                <Input
                  id="capacity_per_hour"
                  type="number"
                  min="0"
                  {...register('capacity_per_hour', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder="e.g. 1200"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="duration_seconds">Duration (seconds)</Label>
                <Input
                  id="duration_seconds"
                  type="number"
                  min="0"
                  {...register('duration_seconds', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder="e.g. 180"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="max_speed_kmh">Max Speed ({getSpeedUnit(measurementSystem)})</Label>
                <Input
                  id="max_speed_kmh"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('max_speed_kmh', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder={measurementSystem === 'imperial' ? 'e.g. 50' : 'e.g. 80.5'}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="max_height_meters">Max Height ({getDistanceUnit(measurementSystem)})</Label>
                <Input
                  id="max_height_meters"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('max_height_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder={measurementSystem === 'imperial' ? 'e.g. 214' : 'e.g. 65.2'}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="length_meters">Length ({getDistanceUnit(measurementSystem)})</Label>
                <Input
                  id="length_meters"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('length_meters', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder={measurementSystem === 'imperial' ? 'e.g. 3937' : 'e.g. 1200.5'}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="inversions">Inversions</Label>
                <Input
                  id="inversions"
                  type="number"
                  min="0"
                  {...register('inversions', { setValueAs: (v) => v === "" ? undefined : parseFloat(v) })}
                  placeholder="e.g. 7"
                />
              </div>
            </div>
          </div>

          {/* Advanced Editors */}
          <div className="space-y-6 border-t pt-6">
            <TechnicalSpecsEditor
              specs={technicalSpecs}
              onChange={setTechnicalSpecs}
              commonSpecs={['Track Material', 'Manufacturer', 'Train Type', 'Restraint System', 'Block Sections']}
            />

            {selectedCategory === 'roller_coaster' && (
              <>
                <CoasterStatsEditor
                  stats={coasterStats}
                  onChange={setCoasterStats}
                />

                <FormerNamesEditor
                  names={formerNames}
                  onChange={setFormerNames}
                  currentName={watch('name') || 'Unnamed Ride'}
                />
              </>
            )}
          </div>

          {/* Submission Context - For Reviewers */}
          <div className="space-y-4 border-t pt-6">
            <div className="flex items-center gap-2 mb-4">
              <Badge variant="secondary" className="text-xs">
                For Moderator Review
              </Badge>
              <p className="text-xs text-muted-foreground">
                Help reviewers verify your submission
              </p>
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="source_url" className="flex items-center gap-2">
                Source URL
                <span className="text-xs text-muted-foreground font-normal">
                  (Optional)
                </span>
              </Label>
              <Input
                id="source_url"
                type="url"
                {...register('source_url')}
                placeholder="https://example.com/article"
              />
              <p className="text-xs text-muted-foreground">
                Where did you find this information? (e.g., official website, news article, press release)
              </p>
              {errors.source_url && (
                <p className="text-sm text-destructive">{errors.source_url.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="submission_notes" className="flex items-center gap-2">
                Notes for Reviewers
                <span className="text-xs text-muted-foreground font-normal">
                  (Optional)
                </span>
              </Label>
              <Textarea
                id="submission_notes"
                {...register('submission_notes')}
                placeholder="Add any context to help moderators verify this information (e.g., 'Confirmed via phone call with park', 'Soft opening date not yet announced')"
                rows={3}
                maxLength={1000}
              />
              <p className="text-xs text-muted-foreground">
                {watch('submission_notes')?.length || 0}/1000 characters
              </p>
              {errors.submission_notes && (
                <p className="text-sm text-destructive">{errors.submission_notes.message}</p>
              )}
            </div>
          </div>

          {/* Images */}
          <EntityMultiImageUploader
            mode={isEditing ? 'edit' : 'create'}
            value={watch('images') || { uploaded: [] }}
            onChange={(images: ImageAssignments) => setValue('images', images)}
            entityType="ride"
            entityId={isEditing ? initialData?.id : undefined}
            currentBannerUrl={initialData?.banner_image_url}
            currentCardUrl={initialData?.card_image_url}
          />

          {/* Form Actions */}
          <div className="flex gap-4 pt-6">
            <Button 
              type="submit"
              className="flex-1"
              loading={isSubmitting}
              loadingText="Saving..."
            >
              <Save className="w-4 h-4 mr-2" />
              {isEditing ? 'Update Ride' : 'Create Ride'}
            </Button>
            
            {onCancel && (
              <Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting}>
                <X className="w-4 h-4 mr-2" />
                Cancel
              </Button>
            )}
          </div>
        </form>

        {/* Park Modal - Add before Manufacturer Modal */}
        <Dialog open={isParkModalOpen} onOpenChange={setIsParkModalOpen}>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create New Park</DialogTitle>
            </DialogHeader>
            <ParkForm
              onSubmit={async (data) => {
                setTempNewPark(data as TempParkData);
                setIsParkModalOpen(false);
                setValue('park_id', undefined);
              }}
              onCancel={() => setIsParkModalOpen(false)}
            />
          </DialogContent>
        </Dialog>

        {/* Designer Modal */}
        <Dialog open={isDesignerModalOpen} onOpenChange={setIsDesignerModalOpen}>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create New Designer</DialogTitle>
            </DialogHeader>
            <ManufacturerForm
              initialData={tempNewDesigner || undefined}
              onSubmit={(data) => {
                setTempNewDesigner(data);
                setIsDesignerModalOpen(false);
                setValue('designer_id', undefined);
              }}
              onCancel={() => setIsDesignerModalOpen(false)}
            />
          </DialogContent>
        </Dialog>

        {/* Manufacturer Modal */}
        <Dialog open={isManufacturerModalOpen} onOpenChange={setIsManufacturerModalOpen}>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {tempNewManufacturer ? 'Edit New Manufacturer' : 'Create New Manufacturer'}
              </DialogTitle>
              <DialogDescription>
                This manufacturer will be submitted for moderation along with the ride.
              </DialogDescription>
            </DialogHeader>
            <ManufacturerForm
              initialData={tempNewManufacturer || undefined}
              onSubmit={(data) => {
                setTempNewManufacturer(data);
                setSelectedManufacturerName(data.name);
                setIsManufacturerModalOpen(false);
                // Clear existing manufacturer selection
                setValue('manufacturer_id', undefined);
                setSelectedManufacturerId('');
                // Clear any existing model
                setValue('ride_model_id', undefined);
                setTempNewRideModel(null);
              }}
              onCancel={() => setIsManufacturerModalOpen(false)}
            />
          </DialogContent>
        </Dialog>

        {/* Ride Model Modal */}
        <Dialog open={isModelModalOpen} onOpenChange={setIsModelModalOpen}>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {tempNewRideModel ? 'Edit New Ride Model' : 'Create New Ride Model'}
              </DialogTitle>
              <DialogDescription>
                Creating a model for: <strong>{selectedManufacturerName || tempNewManufacturer?.name}</strong>
              </DialogDescription>
            </DialogHeader>
            <RideModelForm
              manufacturerName={selectedManufacturerName || tempNewManufacturer?.name || ''}
              manufacturerId={selectedManufacturerId}
              initialData={tempNewRideModel || undefined}
              onSubmit={(data) => {
                setTempNewRideModel(data);
                setIsModelModalOpen(false);
                // Clear existing model selection
                setValue('ride_model_id', undefined);
              }}
              onCancel={() => setIsModelModalOpen(false)}
            />
          </DialogContent>
        </Dialog>
      </CardContent>
    </Card>
  );
}