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 { PhotoUpload } from '@/components/upload/PhotoUpload';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePicker } from '@/components/ui/date-picker';
import { toast } from '@/hooks/use-toast';
import { Zap, Save, X } from 'lucide-react';

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()
});

type RideFormData = z.infer<typeof rideSchema>;

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

export function RideForm({ onSubmit, onCancel, initialData, isEditing = false }: RideFormProps) {
  const [submitting, setSubmitting] = useState(false);
  const [rideImage, setRideImage] = useState<string>(initialData?.image_url || '');

  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 || '',
      height_requirement: initialData?.height_requirement || 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 || undefined,
      max_height_meters: initialData?.max_height_meters || undefined,
      length_meters: initialData?.length_meters || 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 || undefined,
      max_g_force: initialData?.max_g_force || undefined,
      former_names: initialData?.former_names || '',
      coaster_stats: initialData?.coaster_stats || '',
      technical_specs: initialData?.technical_specs || ''
    }
  });

  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 {
      await onSubmit({
        ...data,
        image_url: rideImage || undefined
      });
      
      toast({
        title: isEditing ? "Ride Updated" : "Ride Created",
        description: isEditing 
          ? "The ride information has been updated successfully."
          : "The new ride has been created successfully."
      });
    } 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>

          {/* 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 (cm)</Label>
              <Input
                id="height_requirement"
                type="number"
                min="0"
                {...register('height_requirement', { valueAsNumber: true })}
                placeholder="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 (meters)</Label>
                  <Input
                    id="drop_height_meters"
                    type="number"
                    min="0"
                    step="0.1"
                    {...register('drop_height_meters', { valueAsNumber: true })}
                    placeholder="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 (km/h)</Label>
                <Input
                  id="max_speed_kmh"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('max_speed_kmh', { valueAsNumber: true })}
                  placeholder="e.g. 80.5"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="max_height_meters">Max Height (meters)</Label>
                <Input
                  id="max_height_meters"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('max_height_meters', { valueAsNumber: true })}
                  placeholder="e.g. 65.2"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="length_meters">Length (meters)</Label>
                <Input
                  id="length_meters"
                  type="number"
                  min="0"
                  step="0.1"
                  {...register('length_meters', { valueAsNumber: true })}
                  placeholder="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>

          {/* Image */}
          <div className="space-y-2">
            <Label>Ride Image</Label>
            <PhotoUpload
              maxFiles={1}
              variant="default"
              existingPhotos={rideImage ? [rideImage] : []}
              onUploadComplete={(urls) => setRideImage(urls[0] || '')}
              onError={(error) => {
                toast({
                  title: "Upload Error",
                  description: error,
                  variant: "destructive"
                });
              }}
            />
            <p className="text-xs text-muted-foreground">
              High-quality image of the ride (recommended: 800x600px)
            </p>
          </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>
      </CardContent>
    </Card>
  );
}