import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
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 { UppyPhotoUpload } from '@/components/upload/UppyPhotoUpload';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePicker } from '@/components/ui/date-picker';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Combobox } from '@/components/ui/combobox';
import { toast } from '@/hooks/use-toast';
import { Plus, Zap, Save, X } from 'lucide-react';
import { useUnitPreferences } from '@/hooks/useUnitPreferences';
import { useManufacturers, useRideModels } from '@/hooks/useAutocompleteData';
import { ManufacturerForm } from './ManufacturerForm';
import { RideModelForm } from './RideModelForm';
import { 
  convertSpeed, 
  convertDistance, 
  convertHeight,
  convertSpeedToMetric,
  convertDistanceToMetric,
  convertHeightToMetric,
  getSpeedUnit,
  getDistanceUnit,
  getHeightUnit
} from '@/lib/units';

const rideSchema = z.object({
  name: z.string().min(1, 'Ride name is required'),
  slug: z.string().min(1, 'Slug is required'),
  description: z.string().optional(),
  category: z.string().min(1, 'Category is required'),
  ride_sub_type: z.string().optional(),
  status: z.string().min(1, 'Status is required'),
  opening_date: z.string().optional(),
  closing_date: z.string().optional(),
  height_requirement: z.number().optional(),
  age_requirement: z.number().optional(),
  capacity_per_hour: z.number().optional(),
  duration_seconds: z.number().optional(),
  max_speed_kmh: z.number().optional(),
  max_height_meters: z.number().optional(),
  length_meters: z.number().optional(),
  inversions: z.number().optional(),
  // New roller coaster specific fields
  coaster_type: z.string().optional(),
  seating_type: z.string().optional(),
  intensity_level: z.string().optional(),
  drop_height_meters: z.number().optional(),
  max_g_force: z.number().optional(),
  former_names: z.string().optional(),
  coaster_stats: z.string().optional(),
  technical_specs: z.string().optional(),
  // Manufacturer and model
  manufacturer_id: z.string().uuid().optional(),
  ride_model_id: z.string().uuid().optional()
});

type RideFormData = z.infer<typeof rideSchema>;

interface RideFormProps {
  onSubmit: (data: RideFormData & { 
    image_url?: string;
    banner_image_url?: string;
    banner_image_id?: string;
    card_image_url?: string;
    card_image_id?: string;
  }) => Promise<void>;
  onCancel?: () => void;
  initialData?: Partial<RideFormData & { 
    image_url?: string;
    banner_image_url?: string;
    banner_image_id?: string;
    card_image_url?: string;
    card_image_id?: 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'
];

export function RideForm({ onSubmit, onCancel, initialData, isEditing = false }: RideFormProps) {
  const [submitting, setSubmitting] = useState(false);
  const [bannerImageUrl, setBannerImageUrl] = useState<string>(initialData?.banner_image_url || '');
  const [bannerImageId, setBannerImageId] = useState<string>(initialData?.banner_image_id || '');
  const [cardImageUrl, setCardImageUrl] = useState<string>(initialData?.card_image_url || '');
  const [cardImageId, setCardImageId] = useState<string>(initialData?.card_image_id || '');
  const { preferences } = useUnitPreferences();
  const measurementSystem = preferences.measurement_system;

  // Manufacturer and model state
  const [selectedManufacturerId, setSelectedManufacturerId] = useState<string>(
    initialData?.manufacturer_id || ''
  );
  const [selectedManufacturerName, setSelectedManufacturerName] = useState<string>('');
  const [tempNewManufacturer, setTempNewManufacturer] = useState<any>(null);
  const [tempNewRideModel, setTempNewRideModel] = useState<any>(null);
  const [isManufacturerModalOpen, setIsManufacturerModalOpen] = useState(false);
  const [isModelModalOpen, setIsModelModalOpen] = useState(false);

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

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors }
  } = useForm<RideFormData>({
    resolver: zodResolver(rideSchema),
    defaultValues: {
      name: initialData?.name || '',
      slug: initialData?.slug || '',
      description: initialData?.description || '',
      category: initialData?.category || '',
      ride_sub_type: initialData?.ride_sub_type || '',
      status: initialData?.status || 'Operating',
      opening_date: initialData?.opening_date || '',
      closing_date: initialData?.closing_date || '',
      // Convert metric values to user's preferred unit for display
      height_requirement: initialData?.height_requirement 
        ? convertHeight(initialData.height_requirement, measurementSystem) 
        : 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 
        ? convertSpeed(initialData.max_speed_kmh, measurementSystem) 
        : undefined,
      max_height_meters: initialData?.max_height_meters 
        ? convertDistance(initialData.max_height_meters, measurementSystem) 
        : undefined,
      length_meters: initialData?.length_meters 
        ? convertDistance(initialData.length_meters, measurementSystem) 
        : 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 
        ? convertDistance(initialData.drop_height_meters, measurementSystem) 
        : undefined,
      max_g_force: initialData?.max_g_force || undefined,
      former_names: initialData?.former_names || '',
      coaster_stats: initialData?.coaster_stats || '',
      technical_specs: initialData?.technical_specs || '',
      manufacturer_id: initialData?.manufacturer_id || undefined,
      ride_model_id: initialData?.ride_model_id || undefined
    }
  });

  const selectedCategory = watch('category');

  const generateSlug = (name: string) => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .trim();
  };

  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.value;
    const slug = generateSlug(name);
    setValue('slug', slug);
  };

  const handleFormSubmit = async (data: RideFormData) => {
    setSubmitting(true);
    try {
      // Convert form values back to metric for storage
      const metricData = {
        ...data,
        height_requirement: data.height_requirement 
          ? convertHeightToMetric(data.height_requirement, measurementSystem) 
          : undefined,
        max_speed_kmh: data.max_speed_kmh 
          ? convertSpeedToMetric(data.max_speed_kmh, measurementSystem) 
          : undefined,
        max_height_meters: data.max_height_meters 
          ? convertDistanceToMetric(data.max_height_meters, measurementSystem) 
          : undefined,
        length_meters: data.length_meters 
          ? convertDistanceToMetric(data.length_meters, measurementSystem) 
          : undefined,
        drop_height_meters: data.drop_height_meters 
          ? convertDistanceToMetric(data.drop_height_meters, measurementSystem) 
          : undefined,
        banner_image_url: bannerImageUrl || undefined,
        banner_image_id: bannerImageId || undefined,
        card_image_url: cardImageUrl || undefined,
        card_image_id: cardImageId || undefined
      };

      // Build composite submission if new entities were created
      const submissionContent: any = {
        ride: metricData,
      };
      
      // Add new manufacturer if created
      if (tempNewManufacturer) {
        submissionContent.new_manufacturer = tempNewManufacturer;
        submissionContent.ride.manufacturer_id = null; // Clear since using new
      }
      
      // Add new ride model if created
      if (tempNewRideModel) {
        submissionContent.new_ride_model = tempNewRideModel;
        submissionContent.ride.ride_model_id = null; // Clear since using new
      }

      // Pass composite data to parent
      await onSubmit({
        ...metricData,
        _compositeSubmission: submissionContent
      } as any);
      
      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: any) {
      toast({
        title: "Error",
        description: error.message || "Failed to save ride information.",
        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')}
                onChange={(e) => {
                  register('name').onChange(e);
                  handleNameChange(e);
                }}
                placeholder="Enter ride name"
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="slug">URL Slug *</Label>
              <Input
                id="slug"
                {...register('slug')}
                placeholder="ride-url-slug"
              />
              {errors.slug && (
                <p className="text-sm text-destructive">{errors.slug.message}</p>
              )}
            </div>
          </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 || '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">
            <div className="space-y-2">
              <Label>Opening Date</Label>
              <DatePicker
                date={watch('opening_date') ? new Date(watch('opening_date')) : undefined}
                onSelect={(date) => setValue('opening_date', date ? date.toISOString().split('T')[0] : '')}
                placeholder="Select opening date"
                disableFuture={true}
                fromYear={1800}
              />
            </div>

            <div className="space-y-2">
              <Label>Closing Date (if applicable)</Label>
              <DatePicker
                date={watch('closing_date') ? new Date(watch('closing_date')) : undefined}
                onSelect={(date) => setValue('closing_date', date ? date.toISOString().split('T')[0] : '')}
                placeholder="Select closing date"
                disablePast={false}
                fromYear={1800}
              />
            </div>
          </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', { valueAsNumber: true })}
                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', { valueAsNumber: true })}
                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>

              <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', { valueAsNumber: true })}
                    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', { valueAsNumber: true })}
                    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', { valueAsNumber: true })}
                  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', { valueAsNumber: true })}
                  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', { valueAsNumber: true })}
                  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', { valueAsNumber: true })}
                  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', { valueAsNumber: true })}
                  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', { valueAsNumber: true })}
                  placeholder="e.g. 7"
                />
              </div>
            </div>
          </div>

          {/* Images */}
          <div className="space-y-6">
            <h3 className="text-lg font-semibold">Images</h3>
            
            <div className="space-y-2">
              <Label>Banner Image</Label>
              <UppyPhotoUpload
                maxFiles={1}
                variant="public"
                onUploadComplete={(urls) => {
                  if (urls[0]) {
                    setBannerImageUrl(urls[0]);
                    // Extract image ID from Cloudflare URL (format: https://imagedelivery.net/<hash>/<id>/<variant>)
                    const idMatch = urls[0].match(/\/([^/]+)\/public$/);
                    if (idMatch) {
                      setBannerImageId(idMatch[1]);
                    }
                  }
                }}
                showPreview={true}
              />
              {bannerImageUrl && (
                <div className="mt-2">
                  <img src={bannerImageUrl} alt="Banner preview" className="w-full h-32 object-cover rounded" />
                </div>
              )}
              <p className="text-xs text-muted-foreground">
                High-resolution banner image for the ride detail page (recommended: 1200x400px)
              </p>
            </div>

            <div className="space-y-2">
              <Label>Card Image</Label>
              <UppyPhotoUpload
                maxFiles={1}
                variant="public"
                onUploadComplete={(urls) => {
                  if (urls[0]) {
                    setCardImageUrl(urls[0]);
                    // Extract image ID from Cloudflare URL
                    const idMatch = urls[0].match(/\/([^/]+)\/public$/);
                    if (idMatch) {
                      setCardImageId(idMatch[1]);
                    }
                  }
                }}
                showPreview={true}
              />
              {cardImageUrl && (
                <div className="mt-2">
                  <img src={cardImageUrl} alt="Card preview" className="w-full h-32 object-cover rounded" />
                </div>
              )}
              <p className="text-xs text-muted-foreground">
                Square or rectangular image for ride cards and listings (recommended: 400x300px)
              </p>
            </div>
          </div>

          {/* 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>
  );
}