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, Lock } 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;
  m3u8_url: string | null;
  mp4_url: string | null;
  video_host: 'youtube' | 'adilo' | 'unknown' | null;
  event_start: string | null;
  duration_minutes: number | null;
  chapters?: { time: number; title: string; }[];
  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;
  chapters?: { time: number; title: string; }[];
}

interface UserReview {
  id: string;
  rating: number;
  title: string;
  body: string;
  is_approved: boolean;
  created_at: string;
}

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 [expandedLessonChapters, setExpandedLessonChapters] = useState<Set<string>>(new Set());
  const [userReview, setUserReview] = useState<UserReview | null>(null);
  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,
          chapters
        )
      `)
      .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]));
      }

      // Keep all lesson timelines collapsed by default for cleaner UX
      setExpandedLessonChapters(new Set());
    }
  };

  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, rating, title, body, is_approved, created_at')
      .eq('user_id', user.id)
      .eq('product_id', product.id)
      .order('created_at', { ascending: false })
      .limit(1);

    if (data && data.length > 0) {
      setUserReview(data[0] as UserReview);
    } else {
      setUserReview(null);
    }
  };

  // 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;
  };

  // Check if webinar is currently running or about to start (can join)
  const isWebinarJoinable = () => {
    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);
    const now = new Date();
    // Can join if webinar hasn't ended yet (even if it's already started)
    return now <= 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 formatChapterTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hours > 0) {
      return `${hours}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    }
    return `${mins}:${String(secs).padStart(2, '0')}`;
  };

  const isLastTimelineItem = (length: number, chapterIndex: number)=> {
    const calcLength = length - 1;
    return calcLength !== chapterIndex;
  }

  const renderWebinarChapters = () => {
    if (product?.type !== 'webinar' || !product.chapters || product.chapters.length === 0) return null;

    return (
      <Card className="border-2 border-border mb-6">
        <CardContent className="pt-6">
          <h3 className="text-xl font-bold mb-4">Daftar isi Webinar</h3>
          <div className="space-y-3">
            {product.chapters.map((chapter, index) => (
              <div
                key={index}
                className="flex items-start gap-3 p-3 rounded-lg transition-colors cursor-not-allowed opacity-75"
                title="Beli webinar untuk mengakses konten ini"
              >
                <div className="flex-shrink-0 w-12 text-center">
                  <span className="text-sm font-mono text-muted-foreground">
                    {formatChapterTime(chapter.time)}
                  </span>
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium">{chapter.title}</p>
                </div>
                <Lock className="w-4 h-4 text-muted-foreground flex-shrink-0" />
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    );
  };

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

  const toggleLessonChapters = (lessonId: string) => {
    const newSet = new Set(expandedLessonChapters);
    if (newSet.has(lessonId)) {
      newSet.delete(lessonId);
    } else {
      newSet.add(lessonId);
    }
    setExpandedLessonChapters(newSet);
  };

  // Check if product has any recording (YouTube, M3U8, or MP4)
  const hasRecording = () => {
    if (!product) return false;
    return !!(product.recording_url || product.m3u8_url || product.mp4_url);
  };

  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 (hasRecording()) {
          return (
            <div className="space-y-4">
              <Card className="border-2 border-primary/20 bg-primary/5">
                <CardContent className="pt-6">
                  <div className="flex items-start gap-4">
                    <div className="rounded-full bg-primary/10 p-3">
                      <Play className="w-6 h-6 text-primary" />
                    </div>
                    <div className="flex-1">
                      <h3 className="font-semibold text-lg mb-1">Rekaman webinar tersedia</h3>
                      <p className="text-sm text-muted-foreground mb-4">
                        Akses rekaman webinar kapan saja. Pelajari materi sesuai kecepatan Anda.
                      </p>
                      <Button onClick={() => navigate(`/webinar/${product.slug}`)} size="lg">
                        <Video className="w-4 h-4 mr-2" />
                        Tonton Sekarang
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          );
        }

        // Show "Gabung Webinar" if webinar hasn't ended yet (can join even if already started)
        if (isWebinarJoinable() && product.meeting_link) {
          return (
            <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>
          );
        }

        // Webinar has ended but no recording yet
        if (isWebinarEnded()) {
          return <Badge className="bg-muted text-primary">Rekaman segera tersedia</Badge>;
        }

        return null;
      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-3">
                    {module.lessons.map((lesson) => (
                      <div key={lesson.id} className="space-y-2">
                        {/* Lesson header */}
                        <div 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 className="font-medium">{lesson.title}</span>
                          </div>
                          {lesson.duration_seconds && (
                            <span className="text-muted-foreground">{formatDuration(lesson.duration_seconds)}</span>
                          )}
                        </div>

                        {/* Lesson chapters (if any) */}
                        {lesson.chapters && lesson.chapters.length > 0 && (
                          <Collapsible
                            open={expandedLessonChapters.has(lesson.id)}
                            onOpenChange={() => toggleLessonChapters(lesson.id)}
                          >
                            <CollapsibleTrigger className="flex items-center gap-2 ml-5 mb-2 py-1 px-2 text-xs bg-muted text-muted-foreground hover:bg-accent rounded transition-colors w-full">
                              <Clock className="w-3 h-3" />
                              <span className="flex-1 text-left">
                                {lesson.chapters.length} timeline item{lesson.chapters.length > 1 ? 's' : ''}
                              </span>
                              {expandedLessonChapters.has(lesson.id) ? (
                                <ChevronDown className="w-3 h-3" />
                              ) : (
                                <ChevronRight className="w-3 h-3" />
                              )}
                            </CollapsibleTrigger>
                            <CollapsibleContent>
                              <div className="ml-5 space-y-1">
                                {lesson.chapters.map((chapter, chapterIndex) => (
                                  <div
                                    key={chapterIndex}
                                    className={`flex items-start gap-2 py-1 px-2 text-xs text-muted-foreground rounded transition-colors cursor-not-allowed opacity-60${isLastTimelineItem(lesson.chapters.length, chapterIndex) ? ' border-b-2 border-[#dedede] rounded-none' : ''}`}
                                    title="Beli bootcamp untuk mengakses materi ini"
                                  >
                                    <span className="font-mono w-12 text-center">
                                      {formatChapterTime(chapter.time)}
                                    </span>
                                    <span className="flex-1" dangerouslySetInnerHTML={{ __html: chapter.title }} />
                                    <Lock className="w-3 h-3 flex-shrink-0" />
                                  </div>
                                ))}
                              </div>
                            </CollapsibleContent>
                          </Collapsible>
                        )}
                      </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">
          {/* Ownership Banner - shown at top for purchased users */}
          {hasAccess && (
            <div className="bg-green-50 dark:bg-green-950 border-2 border-green-200 dark:border-green-800 rounded-lg p-4 mb-6">
              <div className="flex items-center justify-between gap-4 flex-wrap">
                <div className="flex items-center gap-3">
                  <CheckCircle className="w-6 h-6 text-green-600 dark:text-green-400 flex-shrink-0" />
                  <div>
                    <p className="font-semibold text-green-900 dark:text-green-100">
                      Anda memiliki akses ke produk ini
                    </p>
                    <p className="text-sm text-green-700 dark:text-green-300">
                      {product.type === 'webinar' && 'Selamat menonton rekaman webinar!'}
                      {product.type === 'bootcamp' && 'Mulai belajar sekarang!'}
                      {product.type === 'consulting' && 'Jadwalkan sesi konsultasi Anda.'}
                    </p>
                  </div>
                </div>
                <Button
                  onClick={() => {
                    if (product.type === 'webinar') {
                      navigate(`/webinar/${product.slug}`);
                    } else if (product.type === 'bootcamp') {
                      navigate(`/bootcamp/${product.slug}`);
                    }
                  }}
                  className="bg-green-600 hover:bg-green-700 text-white shadow-sm"
                >
                  Tonton Sekarang →
                </Button>
              </div>
            </div>
          )}

          <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' && hasRecording() && (
                  <Badge className="bg-secondary text-primary">Rekaman Tersedia</Badge>
                )}
                {product.type === 'webinar' && !hasRecording() && product.event_start && new Date(product.event_start) > new Date() && (
                  <Badge className="bg-brand-accent text-white">Segera Hadir</Badge>
                )}
                {product.type === 'webinar' && !hasRecording() && product.event_start && new Date(product.event_start) <= new Date() && (
                  <Badge className="bg-muted text-primary">Telah Lewat</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>
          )}

          {renderWebinarChapters()}

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

          {/* Webinar review prompt */}
          {hasAccess && product.type === 'webinar' && isWebinarEnded() && (
            <Card className={`border-2 mt-6 ${userReview?.is_approved ? 'bg-gradient-to-br from-brand-accent/10 to-primary/10 border-brand-accent/30' : 'border-primary/20'}`}>
              <CardContent className="py-6">
                {userReview ? (
                  userReview.is_approved ? (
                    // Approved review - celebratory display
                    <div className="space-y-4">
                      <div className="flex items-start gap-3">
                        <div className="rounded-full bg-brand-accent p-2">
                          <CheckCircle className="w-6 h-6 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h3 className="text-lg font-bold">Ulasan Anda Terbit!</h3>
                            <Badge className="bg-brand-accent text-white rounded-full">Disetujui</Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">Terima kasih telah berbagi pengalaman Anda. Ulasan Anda membantu peserta lain!</p>
                        </div>
                      </div>

                      {/* User's review display */}
                      <div className="bg-background/50 backdrop-blur rounded-lg p-4 border border-brand-accent/20">
                        <div className="flex gap-0.5 mb-2">
                          {[1, 2, 3, 4, 5].map((i) => (
                            <Star
                              key={i}
                              className={`w-5 h-5 ${i <= userReview.rating ? 'fill-brand-accent text-brand-accent' : 'text-muted-foreground'}`}
                            />
                          ))}
                        </div>
                        <h4 className="font-semibold text-base mb-1">{userReview.title}</h4>
                        {userReview.body && (
                          <p className="text-sm text-muted-foreground">{userReview.body}</p>
                        )}
                      </div>

                      <div className="text-xs text-muted-foreground">
                        Diterbitkan pada {new Date(userReview.created_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })}
                      </div>
                    </div>
                  ) : (
                    // Pending review
                    <div className="flex items-center gap-3 text-muted-foreground">
                      <div className="rounded-full bg-amber-500/10 p-2">
                        <Clock className="w-5 h-5 text-amber-500" />
                      </div>
                      <div>
                        <p className="font-medium text-foreground">Ulasan Anda sedang ditinjau</p>
                        <p className="text-sm">Terima kasih! Ulasan akan muncul setelah disetujui admin.</p>
                      </div>
                    </div>
                  )
                ) : (
                  // No review yet - prompt to review
                  <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={() => checkUserReview()}
        />
      )}
    </AppLayout>
  );
}
