'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { createClient } from '@/lib/supabase/client';

export default function ProfilePage() {
  const params = useParams();
  const slug = params?.slug as string;
  const supabase = createClient();

  const [profile, setProfile] = useState<any>(null);
  const [details, setDetails] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [notFoundState, setNotFoundState] = useState(false);

  useEffect(() => {
    if (!slug) return;
    const fetchProfile = async () => {
      const { data: p } = await supabase
        .from('marketplace_profiles')
        .select('*')
        .eq('slug', slug)
        .eq('status', 'active')
        .maybeSingle();

      if (!p) { setNotFoundState(true); setLoading(false); return; }
      setProfile(p);

      if (p.profile_type === 'crew') {
        const { data: d } = await supabase
          .from('marketplace_crew_details')
          .select('*')
          .eq('profile_id', p.id)
          .maybeSingle();
        setDetails(d);
      } else {
        const { data: d } = await supabase
          .from('marketplace_vendor_details')
          .select('*')
          .eq('profile_id', p.id)
          .maybeSingle();
        setDetails(d);
      }
      setLoading(false);
    };
    fetchProfile();
  }, [slug]);

  if (loading) {
    return (
      <div className="min-h-screen bg-[#F8FAFC] flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-[#CC0000] border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (notFoundState || !profile || !details) {
    return (
      <div className="min-h-screen bg-[#F8FAFC] text-white flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl mb-4">👤</div>
          <h1 className="text-2xl font-bold mb-2">Profile Not Found</h1>
          <p className="text-gray-400 mb-6">This profile may be pending review or does not exist.</p>
          <Link href="/marketplace/search" className="text-[#CC0000] hover:underline">Browse Directory</Link>
        </div>
      </div>
    );
  }

  const isCrew = profile.profile_type === 'crew';
  const name = isCrew ? details.name : details.company_name;
  const photoUrl = isCrew ? details.headshot_url : details.logo_url;

  return (
    <div className="min-h-screen bg-[#F8FAFC] text-white">
      <Header />
      <div className="max-w-4xl mx-auto px-4 py-24">
        <div className="flex items-center gap-2 text-sm text-gray-500 mb-8">
          <Link href="/marketplace" className="hover:text-[#CC0000]">Marketplace</Link>
          <span>/</span>
          <Link href="/marketplace/search" className="hover:text-[#CC0000]">Search</Link>
          <span>/</span>
          <span className="text-white">{name}</span>
        </div>

        <div className="bg-[#FFFFFF] rounded-2xl overflow-hidden border border-white/10">
          <div className="bg-gradient-to-r from-[#CC0000]/20 to-transparent p-8">
            <div className="flex flex-col sm:flex-row items-start gap-6">
              <div className="w-24 h-24 rounded-full bg-[#CC0000]/20 flex-shrink-0 overflow-hidden flex items-center justify-center text-3xl font-black text-[#CC0000] border-2 border-[#CC0000]/30">
                {photoUrl ? (
                  <img src={photoUrl} alt={`${name} profile photo`} className="w-full h-full object-cover" />
                ) : (
                  name?.charAt(0)?.toUpperCase()
                )}
              </div>
              <div className="flex-1">
                <div className="flex flex-wrap items-center gap-2 mb-2">
                  <h1 className="text-2xl font-black">{name}</h1>
                  {profile.subscription_tier === 'featured' && (
                    <span className="text-xs bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 px-2 py-1 rounded-full font-bold">⭐ Featured</span>
                  )}
                  <span className="text-xs bg-green-500/20 text-green-400 border border-green-500/30 px-2 py-1 rounded-full font-bold">✓ Verified</span>
                  <span className={`text-xs px-2 py-1 rounded-full font-bold ${isCrew ? 'bg-blue-500/20 text-blue-400 border border-blue-500/30' : 'bg-purple-500/20 text-purple-400 border border-purple-500/30'}`}>
                    {isCrew ? 'Crew Member' : 'Vendor / Company'}
                  </span>
                </div>
                <div className="flex flex-wrap gap-4 text-sm text-gray-400">
                  <span>📍 {details.location}</span>
                  {isCrew && details.day_rate && <span>💵 ${details.day_rate.toLocaleString()}/day</span>}
                  {isCrew && details.union_status && details.union_status !== 'non_union' && (
                    <span className="uppercase text-yellow-400">🎭 {details.union_status.replace('_', '-')}</span>
                  )}
                  {!isCrew && details.category && <span>🏢 {details.category}</span>}
                </div>
              </div>
            </div>
          </div>

          <div className="p-8 space-y-8">
            {(details.bio || details.description) && (
              <section>
                <h2 className="text-sm font-bold uppercase tracking-wide text-gray-400 mb-3">About</h2>
                <p className="text-gray-300 leading-relaxed">{details.bio || details.description}</p>
              </section>
            )}

            {isCrew && details.skills && details.skills.length > 0 && (
              <section>
                <h2 className="text-sm font-bold uppercase tracking-wide text-gray-400 mb-3">Skills & Specialties</h2>
                <div className="flex flex-wrap gap-2">
                  {details.skills.map((skill: string) => (
                    <span key={skill} className="text-sm bg-[#CC0000]/10 border border-[#CC0000]/30 text-[#CC0000] px-3 py-1 rounded-full">{skill}</span>
                  ))}
                </div>
              </section>
            )}

            {isCrew && details.equipment && details.equipment.length > 0 && (
              <section>
                <h2 className="text-sm font-bold uppercase tracking-wide text-gray-400 mb-3">Equipment Owned</h2>
                <div className="flex flex-wrap gap-2">
                  {details.equipment.map((item: string) => (
                    <span key={item} className="text-sm bg-white/5 border border-white/10 text-gray-300 px-3 py-1 rounded-full">{item}</span>
                  ))}
                </div>
              </section>
            )}

            {isCrew && details.reel_url && (
              <section>
                <h2 className="text-sm font-bold uppercase tracking-wide text-gray-400 mb-3">Demo Reel</h2>
                <a href={details.reel_url} target="_blank" rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 bg-[#CC0000]/10 hover:bg-[#CC0000]/20 border border-[#CC0000]/30 text-[#CC0000] px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
                  ▶ Watch Reel
                </a>
              </section>
            )}

            {!isCrew && (
              <section>
                <h2 className="text-sm font-bold uppercase tracking-wide text-gray-400 mb-3">Contact & Links</h2>
                <div className="flex flex-wrap gap-3">
                  {details.website && (
                    <a href={details.website} target="_blank" rel="noopener noreferrer"
                      className="inline-flex items-center gap-2 bg-white/5 hover:bg-white/10 border border-white/10 text-white px-4 py-2 rounded-lg text-sm transition-colors">
                      🌐 Website
                    </a>
                  )}
                  {details.contact_email && (
                    <a href={`mailto:${details.contact_email}`}
                      className="inline-flex items-center gap-2 bg-[#CC0000]/10 hover:bg-[#CC0000]/20 border border-[#CC0000]/30 text-[#CC0000] px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
                      ✉ Contact
                    </a>
                  )}
                </div>
              </section>
            )}

            <div className="border-t border-white/10 pt-6 flex items-center justify-between text-xs text-gray-500">
              <span>Member since {new Date(profile.created_at).toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}</span>
              <Link href="/marketplace/search" className="text-[#CC0000] hover:underline">← Back to Search</Link>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}
