import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { AppLayout } from '@/components/AppLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useCart } from '@/contexts/CartContext';
import { toast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';
import { formatIDR } from '@/lib/format';
import { Video, Clock, Calendar, Package, Check, Search, X } from 'lucide-react';
import { Input } from '@/components/ui/input';

interface Product {
  id: string;
  title: string;
  slug: string;
  type: string;
  description: string;
  price: number;
  sale_price: number | null;
  is_active: boolean;
}

interface ConsultingSettings {
  is_consulting_enabled: boolean;
  consulting_block_price: number;
  consulting_block_duration_minutes: number;
}

export default function Products() {
  const [products, setProducts] = useState<Product[]>([]);
  const [consultingSettings, setConsultingSettings] = useState<ConsultingSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState<string>('all');
  const { addItem, items } = useCart();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const [productsRes, consultingRes] = await Promise.all([
      supabase
        .from('products')
        .select('*')
        .eq('is_active', true)
        .order('created_at', { ascending: false }),
      supabase
        .from('consulting_settings')
        .select('is_consulting_enabled, consulting_block_price, consulting_block_duration_minutes')
        .single(),
    ]);

    if (productsRes.error) {
      toast({ title: 'Error', description: 'Gagal memuat produk', variant: 'destructive' });
    } else {
      setProducts(productsRes.data || []);
    }
    
    if (consultingRes.data) {
      setConsultingSettings(consultingRes.data);
    }
    
    setLoading(false);
  };

  const handleAddToCart = (product: Product) => {
    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 = (productId: string) => items.some(item => item.id === productId);

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'consulting': return 'Konsultasi';
      case 'webinar': return 'Webinar';
      case 'bootcamp': return 'Bootcamp';
      default: return type;
    }
  };

  // Strip HTML tags for preview, but keep first 100 chars
  const stripHtml = (html: string) => {
    const tmp = document.createElement('div');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
  };

  // Filter products based on search and type
  const filteredProducts = products.filter((product) => {
    const matchesSearch = product.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         stripHtml(product.description).toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = selectedType === 'all' || product.type === selectedType;
    return matchesSearch && matchesType;
  });

  // Get unique product types for filter
  const productTypes = ['all', ...Array.from(new Set(products.map(p => p.type)))];

  const clearFilters = () => {
    setSearchQuery('');
    setSelectedType('all');
  };

  return (
    <AppLayout>
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold mb-2">Produk</h1>
        <p className="text-muted-foreground mb-4">Jelajahi konsultasi, webinar, dan bootcamp kami</p>

        {/* Consulting Availability Banner */}
        {!loading && consultingSettings?.is_consulting_enabled && (
          <div className="mb-6 p-4 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent border-2 border-primary/30 rounded-xl flex items-center gap-3 hover:border-primary/50 transition-colors">
            <div className="bg-primary text-primary-foreground p-2 rounded-full shrink-0">
              <Video className="w-5 h-5" />
            </div>
            <div>
              <p className="font-semibold">Konsultasi Tersedia!</p>
              <p className="text-sm text-muted-foreground">
                Booking jadwal konsultasi 1-on-1 dengan mentor • {formatIDR(consultingSettings.consulting_block_price)} / {consultingSettings.consulting_block_duration_minutes} menit
              </p>
            </div>
          </div>
        )}

        {/* Search and Filter */}
        {!loading && products.length > 0 && (
          <div className="mb-6 space-y-4">
            {/* Search Bar */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
              <Input
                type="text"
                placeholder="Cari produk..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 border-2"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  <X className="w-5 h-5" />
                </button>
              )}
            </div>

            {/* Category Filter */}
            <div className="flex flex-wrap gap-2 items-center">
              <span className="text-sm font-medium text-muted-foreground">Kategori:</span>
              {productTypes.map((type) => (
                <Button
                  key={type}
                  variant={selectedType === type ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setSelectedType(type)}
                  className={selectedType === type ? 'shadow-sm' : 'border-2'}
                >
                  {type === 'all' ? 'Semua' : getTypeLabel(type)}
                </Button>
              ))}
              {(searchQuery || selectedType !== 'all') && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={clearFilters}
                  className="text-muted-foreground hover:text-destructive"
                >
                  <X className="w-4 h-4 mr-1" />
                  Reset
                </Button>
              )}
            </div>

            {/* Results Count */}
            <p className="text-sm text-muted-foreground">
              Menampilkan {filteredProducts.length} dari {products.length} produk
            </p>
          </div>
        )}

        {loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[...Array(6)].map((_, i) => (
              <Card key={i} className="border-2 border-border">
                <CardHeader>
                  <Skeleton className="h-6 w-3/4" />
                  <Skeleton className="h-4 w-1/4" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-20 w-full" />
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            {/* Consulting Card - Only show when enabled */}
            {consultingSettings?.is_consulting_enabled && (
              <Card className="border-2 border-primary shadow-md hover:shadow-lg transition-all bg-gradient-to-br from-primary/10 to-primary/5 relative overflow-hidden">
                {/* Decorative element */}
                <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2" />

                <CardHeader className="relative">
                  <div className="flex justify-between items-start gap-2">
                    <CardTitle className="text-xl flex items-center gap-2">
                      <Video className="w-5 h-5 text-primary" />
                      Konsultasi 1-on-1
                    </CardTitle>
                    <Badge className="bg-primary text-white shadow-sm shrink-0">
                      Konsultasi
                    </Badge>
                  </div>
                  <CardDescription className="text-base">
                    Sesi konsultasi pribadi dengan mentor. Diskusikan masalah spesifik dan dapatkan solusi langsung.
                  </CardDescription>
                </CardHeader>
                <CardContent className="relative">
                  <div className="space-y-3 mb-4">
                    <div className="flex items-center gap-2 text-sm">
                      <Clock className="w-4 h-4 text-primary" />
                      <span>{consultingSettings.consulting_block_duration_minutes} menit per sesi</span>
                    </div>
                    <div className="flex items-center gap-2 text-sm">
                      <Calendar className="w-4 h-4 text-primary" />
                      <span>Pilih jadwal yang tersedia</span>
                    </div>
                    <div className="flex items-baseline gap-1 pt-2">
                      <span className="text-3xl font-bold text-primary">
                        {formatIDR(consultingSettings.consulting_block_price)}
                      </span>
                      <span className="text-muted-foreground">/ sesi</span>
                    </div>
                  </div>
                  <Link to="/consulting">
                    <Button className="w-full shadow-md hover:shadow-lg transition-shadow">
                      Booking Jadwal
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            )}

            {/* Regular Products */}
            {filteredProducts.map((product) => (
              <Card key={product.id} className="border-2 border-border shadow-sm hover:shadow-md transition-shadow">
                <CardHeader className="pb-4">
                  <div className="flex justify-between items-start gap-2 mb-2">
                    <CardTitle className="text-xl line-clamp-1">{product.title}</CardTitle>
                    <Badge variant="outline" className="shrink-0">
                      {getTypeLabel(product.type)}
                    </Badge>
                  </div>
                  <CardDescription className="line-clamp-2">
                    {stripHtml(product.description)}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="flex items-baseline gap-2 mb-4">
                    {product.sale_price ? (
                      <>
                        <span className="text-3xl font-bold text-primary">
                          {formatIDR(product.sale_price)}
                        </span>
                        <span className="text-lg text-muted-foreground line-through">
                          {formatIDR(product.price)}
                        </span>
                        <Badge variant="destructive" className="ml-2">
                          -{Math.round((1 - product.sale_price / product.price) * 100)}%
                        </Badge>
                      </>
                    ) : (
                      <span className="text-3xl font-bold">{formatIDR(product.price)}</span>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <Link to={`/products/${product.slug}`} className="flex-1">
                      <Button variant="outline" size="default" className="w-full border-2">
                        Lihat Detail
                      </Button>
                    </Link>
                    <Button
                      onClick={() => handleAddToCart(product)}
                      disabled={isInCart(product.id)}
                      size="default"
                      className={isInCart(product.id)
                        ? "bg-green-500 hover:bg-green-600 text-white"
                        : "shadow-sm"
                      }
                    >
                      {isInCart(product.id) ? (
                        <><Check className="w-4 h-4 mr-1" /> Di Keranjang</>
                      ) : (
                        "Tambah"
                      )}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}

            {/* Empty State */}
            {filteredProducts.length === 0 && products.length > 0 && (
              <div className="col-span-full text-center py-16">
                <Search className="w-16 h-16 mx-auto mb-4 text-muted-foreground/50" />
                <h3 className="text-xl font-semibold mb-2">Tidak Ada Produk Ditemukan</h3>
                <p className="text-muted-foreground mb-4">Coba kata kunci atau kategori lain.</p>
                <Button onClick={clearFilters} variant="outline">
                  <X className="w-4 h-4 mr-2" />
                  Reset Filter
                </Button>
              </div>
            )}

            {products.length === 0 && !consultingSettings?.is_consulting_enabled && (
              <div className="col-span-full text-center py-16">
                <Package className="w-16 h-16 mx-auto mb-4 text-muted-foreground/50" />
                <h3 className="text-xl font-semibold mb-2">Belum Ada Produk</h3>
                <p className="text-muted-foreground">Kami sedang mempersiapkan produk menarik untuk Anda.</p>
              </div>
            )}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
