'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { createClient } from '@/lib/supabase/client';
import { useAuth } from '@/contexts/AuthContext';

interface PendingProfile {
  id: string;
  slug: string;
  profile_type: 'crew' | 'vendor';
  status: string;
  created_at: string;
  user_id: string;
  details: any;
  userEmail?: string;
}

export default function AdminQueuePage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const supabase = createClient();

  const [isAdmin, setIsAdmin] = useState(false);
  const [checkingAdmin, setCheckingAdmin] = useState(true);
  const [profiles, setProfiles] = useState<PendingProfile[]>([]);
  const [queueLoading, setQueueLoading] = useState(true);
  const [actionMsg, setActionMsg] = useState<Record<string, string>>({});
  const [rejectionReasons, setRejectionReasons] = useState<Record<string, string>>({});
  const [filter, setFilter] = useState<'pending' | 'active' | 'rejected' | 'all'>('pending');

  useEffect(() => {
    if (!loading && !user) {
      router.replace('/marketplace');
    }
  }, [user, loading, router]);

  useEffect(() => {
    if (!user) return;
    const checkAdmin = async () => {
      const { data } = await supabase.auth.getUser();
      const meta = data.user?.user_metadata || {};
      const appMeta = data.user?.app_metadata || {};
      const adminCheck =
        meta.role === 'admin' ||
        appMeta.role === 'admin' ||
        // Also check user_profiles role column
        false;

      // Also check user_profiles table
      const { data: profile } = await supabase
        .from('user_profiles')
        .select('role')
        .eq('id', user.id)
        .maybeSingle();

      setIsAdmin(adminCheck || profile?.role === 'admin' || profile?.role === 'super_admin');
      setCheckingAdmin(false);
    };
    checkAdmin();
  }, [user, supabase]);

  const fetchQueue = useCallback(async () => {
    setQueueLoading(true);
    let query = supabase
      .from('marketplace_profiles')
      .select('*')
      .order('created_at', { ascending: false });

    if (filter !== 'all') {
      query = query.eq('status', filter);
    }

    const { data: profilesData } = await query;
    if (!profilesData) {
      setProfiles([]);
      setQueueLoading(false);
      return;
    }

    // Fetch details for each profile
    const enriched: PendingProfile[] = [];
    for (const p of profilesData) {
      let details = null;
      if (p.profile_type === 'crew') {
        const { data } = await supabase
          .from('marketplace_crew_details')
          .select('*')
          .eq('profile_id', p.id)
          .maybeSingle();
        details = data;
      } else {
        const { data } = await supabase
          .from('marketplace_vendor_details')
          .select('*')
          .eq('profile_id', p.id)
          .maybeSingle();
        details = data;
      }
      enriched.push({ ...p, details });
    }

    setProfiles(enriched);
    setQueueLoading(false);
  }, [filter, supabase]);

  useEffect(() => {
    if (isAdmin) fetchQueue();
  }, [isAdmin, fetchQueue]);

  const handleApprove = async (profile: PendingProfile) => {
    setActionMsg((prev) => ({ ...prev, [profile.id]: 'Approving...' }));
    try {
      const { error } = await supabase
        .from('marketplace_profiles')
        .update({ status: 'active' })
        .eq('id', profile.id);

      if (error) throw error;

      // Index in Typesense via API
      await fetch('/api/marketplace/typesense-index', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profileId: profile.id }),
      }).catch(() => {}); // Non-blocking

      // Send approval email
      await fetch('/api/marketplace/admin/notify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profileId: profile.id, action: 'approve' }),
      }).catch(() => {});

      setActionMsg((prev) => ({ ...prev, [profile.id]: '✅ Approved' }));
      fetchQueue();
    } catch (err: any) {
      setActionMsg((prev) => ({ ...prev, [profile.id]: `❌ ${err.message}` }));
    }
  };

  const handleReject = async (profile: PendingProfile) => {
    const reason = rejectionReasons[profile.id]?.trim();
    if (!reason) {
      setActionMsg((prev) => ({ ...prev, [profile.id]: '⚠️ Please enter a rejection reason' }));
      return;
    }
    setActionMsg((prev) => ({ ...prev, [profile.id]: 'Rejecting...' }));
    try {
      const { error } = await supabase
        .from('marketplace_profiles')
        .update({ status: 'rejected', rejection_reason: reason })
        .eq('id', profile.id);

      if (error) throw error;

      // Send rejection email
      await fetch('/api/marketplace/admin/notify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profileId: profile.id, action: 'reject', reason }),
      }).catch(() => {});

      setActionMsg((prev) => ({ ...prev, [profile.id]: '✅ Rejected' }));
      fetchQueue();
    } catch (err: any) {
      setActionMsg((prev) => ({ ...prev, [profile.id]: `❌ ${err.message}` }));
    }
  };

  if (loading || checkingAdmin) {
    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 (!isAdmin) {
    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">Access Denied</h1>
          <p className="text-gray-400 mb-6">Admin access required.</p>
          <Link href="/marketplace" className="text-[#CC0000] hover:underline">
            Back to Marketplace
          </Link>
        </div>
      </div>
    );
  }

  const pendingCount = profiles.filter((p) => p.status === 'pending').length;

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

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-3xl font-black uppercase tracking-wide">Profile Approval Queue</h1>
            {pendingCount > 0 && (
              <p className="text-yellow-400 text-sm mt-1">
                ⚠️ {pendingCount} profile{pendingCount !== 1 ? 's' : ''} awaiting review
              </p>
            )}
          </div>
          <button
            onClick={fetchQueue}
            className="text-sm text-[#CC0000] hover:underline font-semibold"
          >
            ↻ Refresh
          </button>
        </div>

        {/* Filter tabs */}
        <div className="flex gap-2 mb-8">
          {(['pending', 'active', 'rejected', 'all'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-4 py-2 rounded-lg text-sm font-bold capitalize transition-colors ${
                filter === f
                  ? 'bg-[#CC0000] text-white'
                  : 'bg-[#FFFFFF] text-gray-400 hover:text-white border border-white/10'
              }`}
            >
              {f}
            </button>
          ))}
        </div>

        {queueLoading ? (
          <div className="flex items-center justify-center py-20">
            <div className="w-8 h-8 border-4 border-[#CC0000] border-t-transparent rounded-full animate-spin" />
          </div>
        ) : profiles.length === 0 ? (
          <div className="text-center py-20 text-gray-500">
            <div className="text-4xl mb-4">✅</div>
            <p className="text-lg font-semibold">
              {filter === 'pending' ? 'No profiles pending review' : `No ${filter} profiles`}
            </p>
          </div>
        ) : (
          <div className="space-y-6">
            {profiles.map((profile) => {
              const name =
                profile.profile_type === 'crew'
                  ? profile.details?.name
                  : profile.details?.company_name;
              const isPending = profile.status === 'pending';

              return (
                <div
                  key={profile.id}
                  className={`bg-[#FFFFFF] rounded-xl border overflow-hidden ${
                    isPending ? 'border-yellow-500/30' : 'border-white/10'
                  }`}
                >
                  <div className="p-6">
                    <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
                      <div className="flex items-start gap-4">
                        {/* Avatar */}
                        <div className="w-14 h-14 rounded-full bg-[#CC0000]/20 flex-shrink-0 overflow-hidden flex items-center justify-center text-xl font-bold text-[#CC0000]">
                          {(profile.details?.headshot_url || profile.details?.logo_url) ? (
                            <img
                              src={profile.details.headshot_url || profile.details.logo_url}
                              alt={`${name} profile photo`}
                              className="w-full h-full object-cover"
                            />
                          ) : (
                            name?.charAt(0)?.toUpperCase() || '?'
                          )}
                        </div>
                        <div>
                          <div className="flex flex-wrap items-center gap-2 mb-1">
                            <span className="font-bold text-lg">{name || 'Unknown'}</span>
                            <span
                              className={`text-xs px-2 py-0.5 rounded-full font-bold ${
                                profile.status === 'active' ?'bg-green-500/20 text-green-400'
                                  : profile.status === 'pending' ?'bg-yellow-500/20 text-yellow-400' :'bg-red-500/20 text-red-400'
                              }`}
                            >
                              {profile.status}
                            </span>
                            <span
                              className={`text-xs px-2 py-0.5 rounded-full font-bold ${
                                profile.profile_type === 'crew' ?'bg-blue-500/20 text-blue-400' :'bg-purple-500/20 text-purple-400'
                              }`}
                            >
                              {profile.profile_type}
                            </span>
                          </div>
                          <div className="text-sm text-gray-400">
                            📍 {profile.details?.location || 'No location'}
                          </div>
                          {profile.profile_type === 'crew' && (
                            <div className="text-sm text-gray-500 mt-0.5">
                              {profile.details?.skills?.slice(0, 3).join(', ') || 'No skills listed'}
                            </div>
                          )}
                          {profile.profile_type === 'vendor' && (
                            <div className="text-sm text-gray-500 mt-0.5">
                              {profile.details?.category || 'No category'}
                            </div>
                          )}
                          <div className="text-xs text-gray-600 mt-1">
                            Submitted{' '}
                            {new Date(profile.created_at).toLocaleDateString('en-US', {
                              month: 'short',
                              day: 'numeric',
                              year: 'numeric',
                            })}
                          </div>
                        </div>
                      </div>

                      {/* Profile details */}
                      <div className="text-sm text-gray-400 space-y-1 min-w-0">
                        {profile.details?.bio && (
                          <p className="text-xs text-gray-500 max-w-xs line-clamp-3">
                            {profile.details.bio}
                          </p>
                        )}
                        {profile.details?.reel_url && (
                          <a
                            href={profile.details.reel_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-xs text-[#CC0000] hover:underline block"
                          >
                            ▶ View Reel
                          </a>
                        )}
                        {profile.details?.website && (
                          <a
                            href={profile.details.website}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-xs text-[#CC0000] hover:underline block"
                          >
                            🌐 Website
                          </a>
                        )}
                      </div>
                    </div>

                    {/* Action area */}
                    {isPending && (
                      <div className="mt-6 pt-6 border-t border-white/10">
                        <div className="flex flex-col sm:flex-row gap-3">
                          <button
                            onClick={() => handleApprove(profile)}
                            className="bg-green-600 hover:bg-green-700 text-white font-bold px-6 py-2.5 rounded-lg text-sm transition-colors"
                          >
                            ✓ Approve
                          </button>
                          <div className="flex flex-1 gap-2">
                            <input
                              value={rejectionReasons[profile.id] || ''}
                              onChange={(e) =>
                                setRejectionReasons((prev) => ({
                                  ...prev,
                                  [profile.id]: e.target.value,
                                }))
                              }
                              className="flex-1 bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-red-500"
                              placeholder="Rejection reason (required)..."
                            />
                            <button
                              onClick={() => handleReject(profile)}
                              className="bg-red-700 hover:bg-red-800 text-white font-bold px-4 py-2.5 rounded-lg text-sm transition-colors whitespace-nowrap"
                            >
                              ✗ Reject
                            </button>
                          </div>
                        </div>
                        {actionMsg[profile.id] && (
                          <p
                            className={`text-sm mt-2 ${
                              actionMsg[profile.id].startsWith('✅')
                                ? 'text-green-400'
                                : actionMsg[profile.id].startsWith('⚠️')
                                ? 'text-yellow-400' :'text-red-400'
                            }`}
                          >
                            {actionMsg[profile.id]}
                          </p>
                        )}
                      </div>
                    )}

                    {!isPending && actionMsg[profile.id] && (
                      <p className="text-sm mt-4 text-gray-400">{actionMsg[profile.id]}</p>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}
