import { useState, useEffect, useCallback, lazy, Suspense } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { AdminFormSkeleton } from '@/components/loading/PageSkeletons';
import { ArrowLeft, FerrisWheel, Building2, Edit } from 'lucide-react';
import { RideModel, Ride, Company } from '@/types/database';
import { supabase } from '@/lib/supabaseClient';
import { useTechnicalSpecifications } from '@/hooks/useTechnicalSpecifications';
import { getCloudflareImageUrl } from '@/lib/cloudflareImageUtils';
import { useAuthModal } from '@/hooks/useAuthModal';
import { useAuth } from '@/hooks/useAuth';
import { toast } from '@/hooks/use-toast';
import { getErrorMessage, handleNonCriticalError } from '@/lib/errorHandler';
import { ManufacturerPhotoGallery } from '@/components/companies/ManufacturerPhotoGallery';

// Lazy load admin form
const RideModelForm = lazy(() => import('@/components/admin/RideModelForm').then(m => ({ default: m.RideModelForm })));
import { VersionIndicator } from '@/components/versioning/VersionIndicator';
import { EntityVersionHistory } from '@/components/versioning/EntityVersionHistory';
import { MetaTags } from '@/components/seo';

export default function RideModelDetail() {
  const { manufacturerSlug, modelSlug } = useParams<{ manufacturerSlug: string; modelSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [model, setModel] = useState<RideModel | null>(null);
  const [manufacturer, setManufacturer] = useState<Company | null>(null);
  const [rides, setRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [statistics, setStatistics] = useState({ rideCount: 0, photoCount: 0 });
  
  // Fetch technical specifications from relational table
  const { data: technicalSpecs } = useTechnicalSpecifications('ride_model', model?.id);

  const fetchData = useCallback(async () => {
    try {
      // Fetch manufacturer
      const { data: manufacturerData, error: manufacturerError } = await supabase
        .from('companies')
        .select('*')
        .eq('slug', manufacturerSlug || '')
        .eq('company_type', 'manufacturer')
        .maybeSingle();

      if (manufacturerError) throw manufacturerError;
      setManufacturer(manufacturerData);

      if (manufacturerData) {
        // Fetch ride model
        const { data: modelData, error: modelError } = await supabase
          .from('ride_models')
          .select('*')
          .eq('slug', modelSlug || '')
          .eq('manufacturer_id', manufacturerData.id)
          .maybeSingle();

        if (modelError) throw modelError;
        setModel(modelData as RideModel);

        if (modelData) {
          // Fetch rides using this model with proper joins
          const { data: ridesData, error: ridesError } = await supabase
            .from('rides')
            .select(`
              *, 
              park:parks!inner(name, slug, location:locations(*)),
              manufacturer:companies!rides_manufacturer_id_fkey(*),
              ride_model:ride_models(id, name, slug, manufacturer_id, category)
            `)
            .eq('ride_model_id', modelData.id)
            .order('name');

          if (ridesError) throw ridesError;
          setRides(ridesData as Ride[] || []);

          // Fetch statistics
          const { count: photoCount } = await supabase
            .from('photos')
            .select('*', { count: 'exact', head: true })
            .eq('entity_type', 'ride_model')
            .eq('entity_id', modelData.id);

          setStatistics({
            rideCount: ridesData?.length || 0,
            photoCount: photoCount || 0
          });
        }
      }
    } catch (error) {
      handleNonCriticalError(error, { action: 'Fetch Ride Model Data', metadata: { manufacturerSlug, modelSlug } });
    } finally {
      setLoading(false);
    }
  }, [manufacturerSlug, modelSlug]);

  useEffect(() => {
    if (manufacturerSlug && modelSlug) {
      fetchData();
    }
  }, [manufacturerSlug, modelSlug, fetchData]);

  const handleEditSubmit = async (data: any) => {
    try {
      if (!user || !model) return;

      const submissionData = {
        ...data,
        manufacturer_id: model.manufacturer_id,
      };

      const { submitRideModelUpdate } = await import('@/lib/entitySubmissionHelpers');
      await submitRideModelUpdate(model.id, submissionData, user.id);
      
      toast({
        title: "Ride Model Updated",
        description: "Your changes have been submitted for review."
      });
      
      setIsEditModalOpen(false);
      fetchData();
    } catch (error) {
      const errorMsg = getErrorMessage(error);
      toast({
        title: "Error",
        description: errorMsg || "Failed to update ride model.",
        variant: "destructive"
      });
    }
  };

  const formatCategory = (category: string | null | undefined) => {
    if (!category) return 'Unknown';
    return category.split('_').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };

  const formatRideType = (type: string | null | undefined) => {
    if (!type) return 'Unknown';
    return type.split('_').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-12 bg-muted rounded w-1/3"></div>
            <div className="h-64 bg-muted rounded"></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="h-48 bg-muted rounded-lg"></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!model || !manufacturer) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Ride Model Not Found</h1>
            <Button onClick={() => navigate(`/manufacturers/${manufacturerSlug}/models`)}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Models
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <MetaTags entityType="ride-model" entitySlug={modelSlug} />
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-between mb-6">
          <Button variant="ghost" onClick={() => navigate(`/manufacturers/${manufacturerSlug}/models`)}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to {manufacturer.name} Models
          </Button>
          
          <Button 
            variant="outline"
            onClick={() => requireAuth(() => setIsEditModalOpen(true), "Sign in to edit this ride model")}
          >
            <Edit className="w-4 h-4 mr-2" />
            Edit Model
          </Button>
        </div>

        {/* Hero Section */}
        <div className="mb-8">
          {(model.banner_image_url || model.banner_image_id) && (
            <div className="relative w-full h-64 mb-6 rounded-lg overflow-hidden">
              <img 
                src={model.banner_image_url || (model.banner_image_id ? getCloudflareImageUrl(model.banner_image_id, 'banner') : '')}
                alt={model.name}
                className="w-full h-full object-cover"
              />
            </div>
          )}

          <div className="flex items-start justify-between mb-4">
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-2">
                <FerrisWheel className="w-8 h-8 text-primary" />
                <h1 className="text-4xl font-bold">{model.name}</h1>
                <VersionIndicator 
                  entityType="ride_model"
                  entityId={model.id}
                  entityName={model.name}
                  compact
                />
              </div>
              
              <div className="flex items-center gap-2 mb-4">
                <Building2 className="w-4 h-4 text-muted-foreground" />
                <Button
                  variant="link"
                  className="p-0 h-auto text-lg"
                  onClick={() => navigate(`/manufacturers/${manufacturerSlug}`)}
                >
                  {manufacturer.name}
                </Button>
              </div>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-2 mb-6">
            <Badge variant="secondary" className="text-sm px-3 py-1">
              {formatCategory(model.category)}
            </Badge>
            {model.ride_type && (
              <Badge variant="outline" className="text-sm px-3 py-1">
                {formatRideType(model.ride_type)}
              </Badge>
            )}
            <Badge variant="outline" className="text-sm px-3 py-1">
              {statistics.rideCount} {statistics.rideCount === 1 ? 'ride' : 'rides'}
            </Badge>
          </div>
        </div>

        <Tabs defaultValue="overview" className="w-full">
          <TabsList className="mb-6">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="rides">Rides ({statistics.rideCount})</TabsTrigger>
            <TabsTrigger value="photos">Photos ({statistics.photoCount})</TabsTrigger>
            <TabsTrigger value="history">History</TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="space-y-6">
            {model.description && (
              <Card>
                <CardContent className="pt-6">
                  <h2 className="text-2xl font-semibold mb-4">About</h2>
                  <p className="text-muted-foreground whitespace-pre-wrap">{model.description}</p>
                </CardContent>
              </Card>
            )}

            {technicalSpecs && technicalSpecs.length > 0 && (
              <Card>
                <CardContent className="pt-6">
                  <h2 className="text-2xl font-semibold mb-4">Technical Specifications</h2>
                  <div className="grid md:grid-cols-2 gap-4">
                    {technicalSpecs.map((spec) => (
                      <div key={spec.id} className="flex justify-between py-2 border-b">
                        <span className="font-medium capitalize">
                          {spec.spec_name.replace(/_/g, ' ')}
                        </span>
                        <span className="text-muted-foreground">
                          {spec.spec_value} {spec.spec_unit || ''}
                        </span>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}
          </TabsContent>

          <TabsContent value="rides">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-2xl font-bold">Rides</h2>
                  <Button 
                    variant="outline" 
                    onClick={() => navigate(`/manufacturers/${manufacturerSlug}/models/${modelSlug}/rides`)}
                  >
                    View All Rides
                  </Button>
                </div>
                <p className="text-muted-foreground">
                  View all {statistics.rideCount} rides using the {model.name} model
                </p>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="photos">
            <ManufacturerPhotoGallery 
              manufacturerId={model.id}
              manufacturerName={model.name}
            />
          </TabsContent>

          <TabsContent value="history">
            <Card>
              <CardContent className="pt-6">
                <EntityVersionHistory
                  entityType="ride_model"
                  entityId={model.id}
                  entityName={model.name}
                />
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Edit Modal */}
        <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <Suspense fallback={<AdminFormSkeleton />}>
              <RideModelForm
                manufacturerName={manufacturer.name}
                manufacturerId={manufacturer.id}
                initialData={{
                  id: model.id,
                  name: model.name,
                  slug: model.slug,
                  category: model.category,
                  ride_type: model.ride_type,
                  description: model.description,
                  banner_image_url: model.banner_image_url,
                  card_image_url: model.card_image_url,
                }}
                onSubmit={handleEditSubmit}
                onCancel={() => setIsEditModalOpen(false)}
              />
            </Suspense>
          </DialogContent>
        </Dialog>
      </main>
    </div>
  );
}
