import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { AppLayout } from '@/components/AppLayout';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useCart } from '@/contexts/CartContext';
import { useAuth } from '@/hooks/useAuth';
import { toast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';
import { formatIDR, formatDuration } from '@/lib/format';
import { Video, Calendar, BookOpen, Play, Clock, ChevronDown, ChevronRight, Star, CheckCircle } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ReviewModal } from '@/components/reviews/ReviewModal';
import { ProductReviews } from '@/components/reviews/ProductReviews';

interface Product {
  id: string;
  title: string;
  slug: string;
  type: string;
  description: string;
  content: string;
  price: number;
  sale_price: number | null;
  meeting_link: string | null;
  recording_url: string | null;
  event_start: string | null;
  duration_minutes: number | null;
  created_at: string;
}

interface Module {
  id: string;
  title: string;
  position: number;
  lessons: Lesson[];
}

interface Lesson {
  id: string;
  title: string;
  duration_seconds: number | null;
  position: number;
}

export default function ProductDetail() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [product, setProduct] = useState<Product | null>(null);
  const [modules, setModules] = useState<Module[]>([]);
  const [loading, setLoading] = useState(true);
  const [hasAccess, setHasAccess] = useState(false);
  const [checkingAccess, setCheckingAccess] = useState(true);
  const [expandedModules, setExpandedModules] = useState<Set<string>>(new Set());
  const [hasReviewed, setHasReviewed] = useState(false);
  const [reviewModalOpen, setReviewModalOpen] = useState(false);
  const { addItem, items } = useCart();
  const { user } = useAuth();

  useEffect(() => {
    if (slug) fetchProduct();
  }, [slug]);

  useEffect(() => {
    if (product && user) {
      checkUserAccess();
      checkUserReview();
    } else {
      setCheckingAccess(false);
    }
  }, [product, user]);

  useEffect(() => {
    if (product?.type === 'bootcamp') {
      fetchCurriculum();
    }
  }, [product]);

  const fetchProduct = async () => {
    const { data, error } = await supabase
      .from('products')
      .select('*')
      .eq('slug', slug)
      .eq('is_active', true)
      .maybeSingle();

    if (error || !data) {
      toast({ title: 'Error', description: 'Produk tidak ditemukan', variant: 'destructive' });
    } else {
      setProduct(data);
    }
    setLoading(false);
  };

  const fetchCurriculum = async () => {
    if (!product) return;
    
    const { data: modulesData } = await supabase
      .from('bootcamp_modules')
      .select(`
        id,
        title,
        position,
        bootcamp_lessons (
          id,
          title,
          duration_seconds,
          position
        )
      `)
      .eq('product_id', product.id)
      .order('position');

    if (modulesData) {
      const sorted = modulesData.map(m => ({
        ...m,
        lessons: (m.bootcamp_lessons as Lesson[]).sort((a, b) => a.position - b.position)
      }));
      setModules(sorted);
      // Expand first module by default
      if (sorted.length > 0) {
        setExpandedModules(new Set([sorted[0].id]));
      }
    }
  };

  const checkUserAccess = async () => {
    if (!product || !user) return;
    
    // Check user_access table first
    const { data: accessData } = await supabase
      .from('user_access')
      .select('id')
      .eq('user_id', user.id)
      .eq('product_id', product.id)
      .maybeSingle();
    
    if (accessData) {
      setHasAccess(true);
      setCheckingAccess(false);
      return;
    }
    
    // Also check for paid orders containing this product
    const { data: paidOrders } = await supabase
      .from('orders')
      .select(`
        id,
        order_items!inner (product_id)
      `)
      .eq('user_id', user.id)
      .eq('payment_status', 'paid')
      .eq('payment_provider', 'pakasir')
      .eq('order_items.product_id', product.id)
      .limit(1);
    
    setHasAccess(!!(paidOrders && paidOrders.length > 0));
    setCheckingAccess(false);
  };

  const checkUserReview = async () => {
    if (!product || !user) return;
    
    const { data } = await supabase
      .from('reviews')
      .select('id')
      .eq('user_id', user.id)
      .eq('product_id', product.id)
      .limit(1);
    
    setHasReviewed(!!(data && data.length > 0));
  };

  // Check if webinar has ended (eligible for review)
  const isWebinarEnded = () => {
    if (!product || product.type !== 'webinar' || !product.event_start) return false;
    const eventStart = new Date(product.event_start);
    const durationMs = (product.duration_minutes || 60) * 60 * 1000;
    const eventEnd = new Date(eventStart.getTime() + durationMs);
    return new Date() > eventEnd;
  };

  const handleAddToCart = () => {
    if (!product) return;
    addItem({ id: product.id, title: product.title, price: product.price, sale_price: product.sale_price, type: product.type });
    toast({ title: 'Ditambahkan', description: `${product.title} sudah ditambahkan ke keranjang` });
  };

  const isInCart = product ? items.some(item => item.id === product.id) : false;

  const getVideoEmbed = (url: string) => {
    const youtubeMatch = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);
    if (youtubeMatch) return `https://www.youtube.com/embed/${youtubeMatch[1]}`;
    const vimeoMatch = url.match(/vimeo\.com\/(\d+)/);
    if (vimeoMatch) return `https://player.vimeo.com/video/${vimeoMatch[1]}`;
    return url;
  };

  const totalDuration = modules.reduce((total, m) => 
    total + m.lessons.reduce((sum, l) => sum + (l.duration_seconds || 0), 0), 0
  );
  const totalLessons = modules.reduce((sum, m) => sum + m.lessons.length, 0);

  const toggleModule = (id: string) => {
    const newSet = new Set(expandedModules);
    if (newSet.has(id)) newSet.delete(id);
    else newSet.add(id);
    setExpandedModules(newSet);
  };

  if (loading) {
    return (<AppLayout><div className="container mx-auto px-4 py-8"><Skeleton className="h-10 w-1/2 mb-4" /><Skeleton className="h-6 w-1/4 mb-8" /><Skeleton className="h-64 w-full" /></div></AppLayout>);
  }

  if (!product) {
    return (<AppLayout><div className="container mx-auto px-4 py-8 text-center"><h1 className="text-2xl font-bold">Produk tidak ditemukan</h1></div></AppLayout>);
  }

  const renderActionButtons = () => {
    if (checkingAccess) return <Skeleton className="h-10 w-40" />;
    
    if (!hasAccess) {
      return (
        <Button onClick={handleAddToCart} disabled={isInCart} size="lg" className="shadow-sm">
          {isInCart ? 'Sudah di Keranjang' : 'Tambah ke Keranjang'}
        </Button>
      );
    }

    switch (product.type) {
      case 'consulting':
        return (
          <Button asChild size="lg" className="shadow-sm">
            <a href={product.meeting_link || '#'} target="_blank" rel="noopener noreferrer">
              <Calendar className="w-4 h-4 mr-2" />
              Jadwalkan Konsultasi
            </a>
          </Button>
        );
      case 'webinar':
        if (product.recording_url) {
          return (
            <div className="space-y-4">
              <div className="aspect-video bg-muted rounded-none overflow-hidden border-2 border-border">
                <iframe
                  src={getVideoEmbed(product.recording_url)}
                  className="w-full h-full"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                />
              </div>
              <Button asChild variant="outline" className="border-2">
                <a href={product.recording_url} target="_blank" rel="noopener noreferrer">
                  <Video className="w-4 h-4 mr-2" />
                  Tonton Rekaman
                </a>
              </Button>
            </div>
          );
        }
        return product.meeting_link ? (
          <Button asChild size="lg" className="shadow-sm">
            <a href={product.meeting_link} target="_blank" rel="noopener noreferrer">
              <Video className="w-4 h-4 mr-2" />
              Gabung Webinar
            </a>
          </Button>
        ) : <Badge className="bg-primary text-primary-foreground">Rekaman segera tersedia</Badge>;
      case 'bootcamp':
        return (
          <Button onClick={() => navigate(`/bootcamp/${product.slug}`)} size="lg" className="shadow-sm">
            <BookOpen className="w-4 h-4 mr-2" />
            Mulai Bootcamp
          </Button>
        );
      default:
        return null;
    }
  };

  const renderCurriculumPreview = () => {
    if (product.type !== 'bootcamp' || modules.length === 0) return null;

    return (
      <Card className="border-2 border-border mb-6">
        <CardContent className="pt-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-xl font-bold">Kurikulum</h3>
            <div className="flex items-center gap-4 text-sm text-muted-foreground">
              <span className="flex items-center gap-1">
                <BookOpen className="w-4 h-4" />
                {totalLessons} Pelajaran
              </span>
              {totalDuration > 0 && (
                <span className="flex items-center gap-1">
                  <Clock className="w-4 h-4" />
                  {formatDuration(totalDuration)}
                </span>
              )}
            </div>
          </div>
          <div className="space-y-2">
            {modules.map((module) => (
              <Collapsible
                key={module.id}
                open={expandedModules.has(module.id)}
                onOpenChange={() => toggleModule(module.id)}
              >
                <CollapsibleTrigger className="flex items-center justify-between w-full p-3 bg-muted hover:bg-accent transition-colors text-left">
                  <span className="font-medium">{module.title}</span>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground">{module.lessons.length} pelajaran</span>
                    {expandedModules.has(module.id) ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent>
                  <div className="border-l-2 border-border ml-4 pl-4 py-2 space-y-2">
                    {module.lessons.map((lesson) => (
                      <div key={lesson.id} className="flex items-center justify-between py-1 text-sm">
                        <div className="flex items-center gap-2">
                          <Play className="w-3 h-3 text-muted-foreground" />
                          <span>{lesson.title}</span>
                        </div>
                        {lesson.duration_seconds && (
                          <span className="text-muted-foreground">{formatDuration(lesson.duration_seconds)}</span>
                        )}
                      </div>
                    ))}
                  </div>
                </CollapsibleContent>
              </Collapsible>
            ))}
          </div>
        </CardContent>
      </Card>
    );
  };

  return (
    <AppLayout>
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          <div className="flex flex-col md:flex-row md:items-start justify-between gap-4 mb-6">
            <div>
              <h1 className="text-4xl font-bold mb-2">{product.title}</h1>
              <div className="flex items-center gap-2 flex-wrap">
                <Badge className="bg-primary text-primary-foreground capitalize">{product.type}</Badge>
                {product.type === 'webinar' && product.recording_url && (
                  <Badge className="bg-secondary text-primary">Rekaman Tersedia</Badge>
                )}
                {product.type === 'webinar' && !product.recording_url && product.event_start && new Date(product.event_start) > new Date() && (
                  <Badge className="bg-brand-accent text-white">Segera Hadir</Badge>
                )}
                {product.type === 'webinar' && !product.recording_url && product.event_start && new Date(product.event_start) <= new Date() && (
                  <Badge className="bg-muted text-primary">Telah Selesai</Badge>
                )}
                {hasAccess && <Badge className="bg-primary text-primary-foreground">Anda memiliki akses</Badge>}
              </div>
            </div>
            <div className="text-right">
              {product.sale_price ? (
                <div>
                  <span className="text-3xl font-bold">{formatIDR(product.sale_price)}</span>
                  <span className="text-muted-foreground line-through ml-2">{formatIDR(product.price)}</span>
                </div>
              ) : (
                <span className="text-3xl font-bold">{formatIDR(product.price)}</span>
              )}
              {product.type === 'bootcamp' && totalDuration > 0 && (
                <p className="text-sm text-muted-foreground mt-1">
                  Total: {formatDuration(totalDuration)} waktu belajar
                </p>
              )}
            </div>
          </div>

          {product.description && (
            <div 
              className="prose max-w-none mb-6 text-muted-foreground"
              dangerouslySetInnerHTML={{ __html: product.description }}
            />
          )}

          {renderCurriculumPreview()}

          {product.content && (
            <Card className="border-2 border-border mb-6">
              <CardContent className="pt-6">
                <div 
                  className="prose max-w-none"
                  dangerouslySetInnerHTML={{ __html: product.content }}
                />
              </CardContent>
            </Card>
          )}

          <div className="flex gap-4 flex-wrap">
            {renderActionButtons()}
          </div>

          {/* Webinar review prompt */}
          {hasAccess && product.type === 'webinar' && isWebinarEnded() && (
            <Card className="border-2 border-primary/20 mt-6">
              <CardContent className="py-4">
                {hasReviewed ? (
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <CheckCircle className="w-5 h-5 text-accent" />
                    <span>Terima kasih atas ulasan Anda (menunggu moderasi)</span>
                  </div>
                ) : (
                  <div className="flex items-center justify-between gap-4 flex-wrap">
                    <div>
                      <p className="font-medium">Bagaimana pengalaman webinar ini?</p>
                      <p className="text-sm text-muted-foreground">Ulasan Anda membantu peserta lain</p>
                    </div>
                    <Button onClick={() => setReviewModalOpen(true)} variant="outline" className="border-2">
                      <Star className="w-4 h-4 mr-2" />
                      Beri ulasan webinar ini
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Product reviews section */}
          <div className="mt-8">
            <ProductReviews productId={product.id} />
          </div>
        </div>
      </div>

      {/* Review Modal */}
      {user && (
        <ReviewModal
          open={reviewModalOpen}
          onOpenChange={setReviewModalOpen}
          userId={user.id}
          productId={product.id}
          type="webinar"
          contextLabel={product.title}
          onSuccess={() => setHasReviewed(true)}
        />
      )}
    </AppLayout>
  );
}
