'use client';

import {
  CheckCircle2, MessageSquare, Share2, Plus, Search,
  Settings, ChevronRight, Star, Clock, ShoppingBag, ArrowRight,
  Shield, User, ExternalLink, Loader2, AlertCircle, Zap, ShoppingCart,
  MoreVertical, Heart
} from 'lucide-react';
import Link from 'next/link';
import { useState, useEffect, use } from 'react';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import ProductImageWithFallback from '@/components/ProductImageWithFallback';

export default function PublicSellerProfilePage({ params }: { params: Promise<{ locale: string; id: string }> }) {
  const { locale, id } = use(params);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [profile, setProfile] = useState<any>(null);

  // Filter states
  const [priceRange, setPriceRange] = useState([0, 100000000]);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [sortBy, setSortBy] = useState('newest');
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    api.get(`/sellers/${id}`)
      .then(res => {
        setProfile(res.data);
      })
      .catch(err => {
        console.error(err);
        setError(err.response?.data?.message || 'Không thể tải thông tin gian hàng');
      })
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) {
    return (
      <div className="min-h-screen bg-[#0a0b0d] flex items-center justify-center">
        <Loader2 className="w-10 h-10 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !profile) {
    return (
      <div className="min-h-screen bg-[#0a0b0d] flex flex-col items-center justify-center text-center px-4">
        <AlertCircle className="w-16 h-16 text-red-500 mb-4" />
        <h1 className="text-2xl font-bold text-white mb-2">Gian hàng không tồn tại</h1>
        <p className="text-gray-400 mb-6">{error}</p>
        <Link href="/" className="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-colors">
          Về trang chủ
        </Link>
      </div>
    );
  }

  const joinDate = new Date(profile.user.createdAt).toLocaleDateString('vi-VN');
  const completedOrders = profile.user.sellerOrders?.length || 0;
  const policies = profile.policies || [];
  const faqs = profile.faqs || [];
  let products = profile.products || [];
  const rating = profile.rating || { average: 0, count: 0, percentage: 0 };

  // Filter & sort products
  products = products.filter((prod: any) => {
    const price = prod.price || 0;
    const matchPrice = price >= priceRange[0] && price <= priceRange[1];
    const matchCategory = !selectedCategory || prod.category?.id === selectedCategory;
    const matchSearch = !searchQuery || prod.name.toLowerCase().includes(searchQuery.toLowerCase());
    return matchPrice && matchCategory && matchSearch;
  });

  if (sortBy === 'price-asc') {
    products.sort((a: any, b: any) => (a.price || 0) - (b.price || 0));
  } else if (sortBy === 'price-desc') {
    products.sort((a: any, b: any) => (b.price || 0) - (a.price || 0));
  }

  const categories = [...new Set(profile.products?.map((p: any) => p.category))].filter(Boolean);

  return (
    <div className="min-h-screen bg-[#0a0b0d] pb-20">

      {/* 1. Header Banner */}
      <div className="relative">
        <div className="h-64 md:h-80 w-full relative overflow-hidden bg-gradient-to-r from-blue-900 to-purple-900">
          {profile.bannerUrl ? (
            <img src={profile.bannerUrl} alt="Banner" className="w-full h-full object-cover" />
          ) : (
            <div className="absolute inset-0 bg-gradient-to-r from-indigo-900 to-purple-900">
              <div className="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/cubes.png')] opacity-20"></div>
            </div>
          )}

          {!profile.bannerUrl && (
            <div className="absolute inset-0 flex flex-col items-center justify-center text-center p-6 bg-black/40">
              <h1 className="text-2xl md:text-4xl font-black text-white uppercase drop-shadow-lg tracking-wider max-w-4xl">
                {profile.shopName}
              </h1>
              <p className="text-gray-300 mt-2 text-sm md:text-base">/{profile.shopSlug}</p>
            </div>
          )}
          {profile.bannerUrl && (
            <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex flex-col items-start justify-end p-8">
              <h1 className="text-2xl md:text-4xl font-black text-white uppercase drop-shadow-lg tracking-wider">
                {profile.shopName}
              </h1>
              <p className="text-gray-300 mt-1 text-sm">/{profile.shopSlug}</p>
            </div>
          )}
        </div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative -mt-16 md:-mt-20 flex flex-col md:flex-row items-end justify-between gap-6">
          <div className="flex flex-col md:flex-row items-center md:items-end gap-6">
            <div className="w-32 h-32 md:w-40 md:h-40 rounded-full border-4 border-[#0a0b0d] overflow-hidden bg-gradient-to-br from-indigo-700 to-purple-700 relative flex-shrink-0 shadow-2xl">
              {profile.avatarUrl ? (
                <img src={profile.avatarUrl} alt={profile.shopName} className="w-full h-full object-cover" />
              ) : (
                <div className="absolute inset-0 flex items-center justify-center text-white text-5xl font-bold">
                  {profile.shopName.charAt(0).toUpperCase()}
                </div>
              )}
              <div className="absolute bottom-2 left-1/2 -translate-x-1/2 bg-green-500 text-black text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1 border border-black">
                <div className="w-1.5 h-1.5 bg-black rounded-full"></div> Đang online
              </div>
            </div>

            <div className="flex gap-2 mb-2 md:mb-6">
              <span className="bg-yellow-500/20 text-yellow-500 px-3 py-1 rounded-md text-xs font-bold border border-yellow-500/30">New Seller</span>
              <span className="bg-green-500/20 text-green-500 px-3 py-1 rounded-md text-xs font-bold border border-green-500/30">Uy tín</span>
            </div>
          </div>

          <div className="flex gap-3 mb-2 md:mb-6">
            <button className="bg-white text-black hover:bg-gray-200 px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition">
              <Plus className="w-4 h-4" /> Theo dõi
            </button>
            <button className="bg-white/10 text-white hover:bg-white/20 border border-white/20 px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition">
              <Share2 className="w-4 h-4" /> Chia sẻ
            </button>
            <button className="bg-white/10 text-white hover:bg-white/20 border border-white/20 px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition">
              <MessageSquare className="w-4 h-4" /> Nhắn tin
            </button>
          </div>
        </div>

        {/* Stats bar */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-6">
          <div className="flex flex-wrap items-center justify-center md:justify-start gap-8 py-4 border-y border-white/10">
            <div className="flex items-center gap-2 text-sm">
              <Star className="w-5 h-5 text-yellow-500 fill-current" />
              <span className="text-white font-bold">{rating.count ? Number(rating.average).toFixed(1) : '—'}</span>
              <span className="text-gray-500">({rating.count} đánh giá · {rating.percentage}%)</span>
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-400">
              <User className="w-4 h-4" /> <strong className="text-white">0</strong> người theo dõi
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-400">
              <ShoppingBag className="w-4 h-4" /> <strong className="text-white">{products.length}</strong> sản phẩm
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-400">
              <Clock className="w-4 h-4" /> <strong className="text-white">Nhanh</strong> giao trung bình
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-400">
              <CheckCircle2 className="w-4 h-4 text-green-500" /> <strong className="text-white">{completedOrders}</strong> đơn hoàn thành
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-8 flex flex-col lg:flex-row gap-6">

        {/* Sidebar Filter */}
        <div className="w-full lg:w-64 shrink-0">
          <div className="sticky top-20 space-y-4">
            {/* Search */}
            <div className="bg-[#15161a] rounded-xl p-4 border border-white/5">
              <input
                type="text"
                placeholder="Tìm kiếm sản phẩm..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-[#0a0b0d] border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder:text-gray-600 focus:outline-none focus:border-primary"
              />
            </div>

            {/* Price Range */}
            <div className="bg-[#15161a] rounded-xl p-4 border border-white/5">
              <h3 className="text-sm font-bold text-white mb-4">Khoảng giá</h3>
              <div className="space-y-3">
                <input
                  type="range"
                  min="0"
                  max="100000000"
                  step="100000"
                  value={priceRange[1]}
                  onChange={(e) => setPriceRange([0, Number(e.target.value)])}
                  className="w-full h-1 bg-white/20 rounded-full accent-primary"
                />
                <div className="flex justify-between text-xs text-gray-400">
                  <span>0 ₫</span>
                  <span>{(priceRange[1] / 1000000).toFixed(0)}M ₫</span>
                </div>
              </div>
            </div>

            {/* Categories */}
            {categories.length > 0 && (
              <div className="bg-[#15161a] rounded-xl p-4 border border-white/5">
                <h3 className="text-sm font-bold text-white mb-4">Danh mục</h3>
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  <button
                    onClick={() => setSelectedCategory('')}
                    className={`block w-full text-left px-3 py-2 rounded-lg text-sm transition ${
                      !selectedCategory
                        ? 'bg-primary text-white'
                        : 'text-gray-400 hover:bg-white/5'
                    }`}
                  >
                    Tất cả
                  </button>
                  {categories.map((cat: any) => (
                    <button
                      key={cat.id}
                      onClick={() => setSelectedCategory(cat.id)}
                      className={`block w-full text-left px-3 py-2 rounded-lg text-sm transition ${
                        selectedCategory === cat.id
                          ? 'bg-primary text-white'
                          : 'text-gray-400 hover:bg-white/5'
                      }`}
                    >
                      {cat.name}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Sort */}
            <div className="bg-[#15161a] rounded-xl p-4 border border-white/5">
              <h3 className="text-sm font-bold text-white mb-4">Sắp xếp</h3>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="w-full bg-[#0a0b0d] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-primary"
              >
                <option value="newest">Mới nhất</option>
                <option value="price-asc">Giá tăng dần</option>
                <option value="price-desc">Giá giảm dần</option>
              </select>
            </div>
          </div>
        </div>

        {/* Main Content - Products */}
        <div className="flex-1 space-y-6">

          {/* Sản phẩm của shop */}
          <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
              <div className="flex items-center gap-3">
                <h2 className="text-lg font-bold text-white">Sản phẩm</h2>
                <span className="bg-white/10 text-xs px-2 py-1 rounded text-gray-300">{products.length}</span>
              </div>
            </div>

            {products.length === 0 ? (
              <p className="text-sm text-gray-500 text-center py-8">Không tìm thấy sản phẩm phù hợp.</p>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {products.map((prod: any) => (
                  <Link key={prod.id} href={`/${locale}/product/${prod.slug}`} className="bg-[#0a0b0d] rounded-xl overflow-hidden border border-white/10 group hover:border-primary/50 transition">
                    <div className="h-40 bg-gradient-to-r from-purple-900 to-indigo-900 relative flex items-center justify-center p-4 text-center">
                      {prod.images?.[0]?.url ? (
                        <ProductImageWithFallback src={prod.images[0].url} alt={prod.name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300" />
                      ) : (
                        <h3 className="text-white font-black text-xl uppercase drop-shadow-md line-clamp-2">
                          {prod.name}
                        </h3>
                      )}
                    </div>
                    <div className="p-4">
                      <h4 className="text-white font-bold text-sm mb-1 line-clamp-2">{prod.name}</h4>
                      <p className="text-xs text-gray-500 mb-3 truncate">{prod.category?.name || 'Danh mục chung'}</p>
                      <div className="flex items-end justify-between mb-3">
                        <div className="text-lg font-bold text-white">{Number(prod.price).toLocaleString()} ₫</div>
                        <Heart className="w-4 h-4 text-gray-500 hover:text-red-500 cursor-pointer" />
                      </div>
                      <div className="flex items-center gap-3 text-xs text-gray-400 mb-4">
                        <span className="flex items-center gap-1 text-yellow-500"><Star className="w-3 h-3 fill-current"/> 0.0</span>
                        <span className="flex items-center gap-1"><ShoppingCart className="w-3 h-3"/> Bán 0</span>
                      </div>
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-green-500 flex items-center gap-1 text-[10px] font-bold"><CheckCircle2 className="w-3 h-3"/> {prod.stock > 0 ? 'Còn hàng' : 'Hết hàng'}</span>
                        <button className="text-primary text-[10px] font-bold hover:underline">Chi tiết</button>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>

          {/* Giới thiệu */}
          {profile.description && (
            <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
              <h2 className="text-lg font-bold text-white mb-4">Giới thiệu</h2>
              <div className="text-sm text-gray-300 space-y-4 font-mono leading-relaxed whitespace-pre-wrap">
                {profile.description}
              </div>
            </div>
          )}

          {/* Chính sách của shop */}
          {policies.length > 0 && (
            <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
              <h2 className="text-lg font-bold text-white mb-4">Chính sách của shop</h2>
              <div className="space-y-4">
                {policies.map((p: any, i: number) => (
                  <div key={i} className="bg-[#0a0b0d] border border-white/10 rounded-xl p-4 flex gap-4">
                    <div className="mt-1"><Shield className="w-5 h-5 text-gray-400" /></div>
                    <div>
                      <h4 className="font-bold text-white text-sm">{p.title}</h4>
                      <p className="text-xs text-gray-400 mt-1 leading-relaxed whitespace-pre-wrap">
                        {p.content}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Đánh giá shop */}
            <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
              <h2 className="text-lg font-bold text-white mb-6">Đánh giá shop</h2>

              <div className="flex items-center gap-6 mb-8">
                <div className="text-center">
                  <div className="text-4xl font-black text-white mb-1">5.0</div>
                  <div className="flex text-yellow-500 mb-1 justify-center">
                    <Star className="w-4 h-4 fill-current"/><Star className="w-4 h-4 fill-current"/><Star className="w-4 h-4 fill-current"/><Star className="w-4 h-4 fill-current"/><Star className="w-4 h-4 fill-current"/>
                  </div>
                  <div className="text-xs text-gray-500">(0 đánh giá)</div>
                </div>

                <div className="flex-1 space-y-2">
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <span className="w-4">5★</span>
                    <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden"><div className="w-full h-full bg-yellow-500"></div></div>
                    <span className="w-8 text-right">100%</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <span className="w-4">4★</span>
                    <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden"></div>
                    <span className="w-8 text-right">0%</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <span className="w-4">3★</span>
                    <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden"></div>
                    <span className="w-8 text-right">0%</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <span className="w-4">2★</span>
                    <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden"></div>
                    <span className="w-8 text-right">0%</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <span className="w-4">1★</span>
                    <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden"></div>
                    <span className="w-8 text-right">0%</span>
                  </div>
                </div>
              </div>

              <div className="bg-[#0a0b0d] p-4 rounded-xl border border-white/10">
                <p className="text-sm text-gray-400 text-center">Chưa có đánh giá nào.</p>
              </div>
            </div>

            {/* FAQ */}
            <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
              <h2 className="text-lg font-bold text-white mb-6">Câu hỏi thường gặp</h2>
              {faqs.length === 0 ? (
                <p className="text-sm text-gray-500 text-center">Gian hàng chưa cập nhật câu hỏi thường gặp.</p>
              ) : (
                <div className="space-y-4">
                  {faqs.map((f: any, i: number) => (
                    <div key={i} className="bg-[#0a0b0d] rounded-xl p-4 border border-white/10 cursor-pointer hover:border-primary/50 transition">
                      <div className="flex justify-between items-start mb-3">
                        <div className="flex gap-2">
                          <span className="text-green-500 font-black text-lg leading-none">?</span>
                          <h4 className="text-sm font-bold text-white">{f.question}</h4>
                        </div>
                        <ChevronRight className="w-4 h-4 text-gray-500" />
                      </div>
                      <p className="text-xs text-gray-400 leading-relaxed pl-5 whitespace-pre-wrap">
                        {f.answer}
                      </p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

        </div>

        {/* Right Column (Sidebar) */}
        <div className="w-full lg:w-80 shrink-0 space-y-6">

          {/* Thông tin người bán */}
          <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
            <h3 className="text-base font-bold text-white mb-4">Thông tin người bán</h3>
            <div className="space-y-4">
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><ShoppingBag className="w-4 h-4"/> Đã bán</span>
                <span className="text-white font-bold">{completedOrders}</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><Star className="w-4 h-4"/> Đánh giá</span>
                <span className="text-white font-bold">5.0 (0)</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><Clock className="w-4 h-4"/> Giờ hỗ trợ</span>
                <span className="text-white font-bold">{profile.supportHours || 'Chưa cập nhật'}</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><User className="w-4 h-4"/> Tham gia từ</span>
                <span className="text-white font-bold">{joinDate}</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><CheckCircle2 className="w-4 h-4"/> Tỉ lệ hoàn thành</span>
                <span className="text-white font-bold">100%</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><ShoppingBag className="w-4 h-4"/> Sản phẩm đang bán</span>
                <span className="text-white font-bold">{products.length}</span>
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400 flex items-center gap-2"><Shield className="w-4 h-4"/> Tỉ lệ khiếu nại</span>
                <span className="text-white font-bold">0%</span>
              </div>
              <div className="flex flex-col gap-3 pt-4 border-t border-white/10">
                <div className="space-y-2">
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide">Liên kết mạng xã hội</p>
                  <div className="grid grid-cols-2 gap-2">
                    {profile.facebookUrl && (
                      <a href={profile.facebookUrl} target="_blank" rel="noreferrer" className="text-xs text-blue-400 hover:text-blue-300 truncate">Facebook</a>
                    )}
                    {profile.discordUrl && (
                      <a href={profile.discordUrl} target="_blank" rel="noreferrer" className="text-xs text-indigo-400 hover:text-indigo-300 truncate">Discord</a>
                    )}
                    {profile.youtubeUrl && (
                      <a href={profile.youtubeUrl} target="_blank" rel="noreferrer" className="text-xs text-red-400 hover:text-red-300 truncate">YouTube</a>
                    )}
                    {profile.telegramUrl && (
                      <a href={profile.telegramUrl} target="_blank" rel="noreferrer" className="text-xs text-cyan-400 hover:text-cyan-300 truncate">Telegram</a>
                    )}
                    {!profile.facebookUrl && !profile.discordUrl && !profile.youtubeUrl && !profile.telegramUrl && (
                      <p className="text-xs text-gray-500 col-span-2">Chưa có liên kết mạng xã hội.</p>
                    )}
                  </div>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-400 flex items-center gap-2"><Settings className="w-4 h-4"/> Cấp độ người bán</span>
                  <span className="text-yellow-500 font-bold">New Seller</span>
                </div>
              </div>
            </div>
          </div>

          {/* Thông báo từ shop */}
          {profile.announcement && (
            <div className="bg-primary/10 border border-primary/20 rounded-xl p-5">
              <h4 className="text-sm font-bold text-primary flex items-center gap-2 mb-2">
                <MessageSquare className="w-4 h-4" /> Thông báo từ shop
              </h4>
              <p className="text-xs text-gray-300 leading-relaxed whitespace-pre-wrap">
                {profile.announcement}
              </p>
            </div>
          )}

          {/* Trung tâm uy tín */}
          <div className="bg-[#15161a] rounded-xl p-6 border border-white/5">
            <h3 className="text-base font-bold text-white mb-4">Trung tâm uy tín</h3>
            <div className="space-y-3">
              <div className="flex items-start gap-2 text-sm text-gray-300">
                <CheckCircle2 className="w-4 h-4 text-green-500 mt-0.5 shrink-0" />
                <span>Hồ sơ người bán đang hiển thị công khai</span>
              </div>
              <div className="flex items-start gap-2 text-sm text-gray-300">
                <CheckCircle2 className="w-4 h-4 text-green-500 mt-0.5 shrink-0" />
                <span>{completedOrders} đơn đã hoàn thành</span>
              </div>
              <div className="flex items-start gap-2 text-sm text-gray-300">
                <CheckCircle2 className="w-4 h-4 text-green-500 mt-0.5 shrink-0" />
                <span>Chưa ghi nhận khiếu nại công khai</span>
              </div>
            </div>
          </div>

        </div>

      </div>
    </div>
  );
}
