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 type { RideTechnicalSpec, RideCoasterStat, RideNameHistory } from '@/types/database';
import type { TempCompanyData, TempRideModelData } from '@/types/company';
import { entitySchemas } 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 { toast } from '@/hooks/use-toast';
import { getErrorMessage } from '@/lib/errorHandler';
import { Plus, Zap, Save, X } from 'lucide-react';
import { toDateOnly } from '@/lib/dateUtils';
import { useUnitPreferences } from '@/hooks/useUnitPreferences';
import { useManufacturers, useRideModels } from '@/hooks/useAutocompleteData';
import { useUserRole } from '@/hooks/useUserRole';
import { ManufacturerForm } from './ManufacturerForm';
import { RideModelForm } from './RideModelForm';
import { TechnicalSpecsEditor } from './editors/TechnicalSpecsEditor';
import { CoasterStatsEditor } 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) => Promise<void>;
  onCancel?: () => void;
  initialData?: Partial<RideFormData & {
    id?: string;
    banner_image_url?: string;
    card_image_url?: string;
  }>;
  isEditing?: boolean;
}

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

const statusOptions = [
  'Operating',
  'Seasonal',
  'Closed Temporarily',
  'Closed Permanently',
  'Under Construction',
  'Planned',
  'SBNO' // Standing But Not Operating
];

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

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

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

// Status value mappings between display (form) and database values
const STATUS_DISPLAY_TO_DB: Record<string, string> = {
  'Operating': 'operating',
  'Seasonal': 'operating',
  'Closed Temporarily': 'maintenance',
  'Closed Permanently': 'closed',
  'Under Construction': 'under_construction',
  'Planned': 'under_construction',
  'SBNO': 'sbno'
};

const STATUS_DB_TO_DISPLAY: Record<string, string> = {
  'operating': 'Operating',
  'closed': 'Closed Permanently',
  'under_construction': 'Under Construction',
  'maintenance': 'Closed Temporarily',
  'sbno': 'SBNO'
};

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

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

  // Manufacturer and model state
  const [selectedManufacturerId, setSelectedManufacturerId] = useState<string>(
    initialData?.manufacturer_id || ''
  );
  const [selectedManufacturerName, setSelectedManufacturerName] = useState<string>('');
  const [tempNewManufacturer, setTempNewManufacturer] = useState<TempCompanyData | null>(null);
  const [tempNewRideModel, setTempNewRideModel] = useState<TempRideModelData | null>(null);
  const [isManufacturerModalOpen, setIsManufacturerModalOpen] = 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 {
    register,
    handleSubmit,
    setValue,
    watch,
    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 
        ? STATUS_DB_TO_DISPLAY[initialData.status] || 'Operating'
        : 'Operating',
      opening_date: initialData?.opening_date || '',
      opening_date_precision: initialData?.opening_date_precision || 'day',
      closing_date: initialData?.closing_date || '',
      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,
      images: { uploaded: [] }
    }
  });

  const selectedCategory = watch('category');


  const handleFormSubmit = async (data: RideFormData) => {
    setSubmitting(true);
    try {
      // Transform status from display value to DB value
      const dbStatus = STATUS_DISPLAY_TO_DB[data.status] || 'operating';
      
      // Convert form values back to metric for storage
      const metricData = {
        ...data,
        status: dbStatus,
        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,
        _tempNewManufacturer: tempNewManufacturer,
        _tempNewRideModel: tempNewRideModel
      };

      // 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) {
      const errorMsg = getErrorMessage(error);
      toast({
        title: "Error",
        description: errorMsg,
        variant: "destructive"
      });
    } finally {
      setSubmitting(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>

          {/* 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)} 
                defaultValue={initialData?.status 
                  ? STATUS_DB_TO_DISPLAY[initialData.status] || 'Operating'
                  : 'Operating'
                }
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map((status) => (
                    <SelectItem key={status} value={status}>
                      {status}
                    </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')}
                    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')}
                        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') ? new Date(watch('opening_date')) : undefined}
              precision={(watch('opening_date_precision') as DatePrecision) || 'day'}
              onChange={(date, precision) => {
                setValue('opening_date', date ? toDateOnly(date) : undefined);
                setValue('opening_date_precision', precision);
              }}
              label="Opening Date"
              placeholder="Select opening date"
              disableFuture={true}
              fromYear={1800}
            />

            <FlexibleDateInput
              value={watch('closing_date') ? new Date(watch('closing_date')) : undefined}
              precision={(watch('closing_date_precision') as DatePrecision) || 'day'}
              onChange={(date, precision) => {
                setValue('closing_date', date ? toDateOnly(date) : 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}>
                    <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}>
                    <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}>
                    <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-2">
                  <Label>Track Material</Label>
                  <Select 
                    onValueChange={(value) => setValue('track_material', value === '' ? undefined : value as 'wood' | 'steel' | 'hybrid' | 'aluminum' | 'other')} 
                    defaultValue={initialData?.track_material || ''}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select track material" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="">None</SelectItem>
                      <SelectItem value="wood">Wood</SelectItem>
                      <SelectItem value="steel">Steel</SelectItem>
                      <SelectItem value="hybrid">Hybrid (Wood/Steel)</SelectItem>
                      <SelectItem value="aluminum">Aluminum</SelectItem>
                      <SelectItem value="other">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </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>
          )}

          {/* 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>

          {/* 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" disabled={submitting} className="flex-1">
              <Save className="w-4 h-4 mr-2" />
              {submitting ? 'Saving...' : (isEditing ? 'Update Ride' : 'Create Ride')}
            </Button>
            
            {onCancel && (
              <Button type="button" variant="outline" onClick={onCancel}>
                <X className="w-4 h-4 mr-2" />
                Cancel
              </Button>
            )}
          </div>
        </form>

        {/* 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}
              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}
              onSubmit={(data) => {
                setTempNewRideModel(data);
                setIsModelModalOpen(false);
                // Clear existing model selection
                setValue('ride_model_id', undefined);
              }}
              onCancel={() => setIsModelModalOpen(false)}
            />
          </DialogContent>
        </Dialog>
      </CardContent>
    </Card>
  );
}