'use client';

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

const GIG_TYPES = [
  'Commercial',
  'Documentary',
  'Corporate Video',
  'Live Event',
  'News / ENG',
  'Sports',
  'Music Video',
  'Film',
  'Streaming / OTT',
  'Social Media',
  'Other',
];

const JOB_TYPES = [
  { value: 'full_time', label: 'Full-Time' },
  { value: 'part_time', label: 'Part-Time' },
  { value: 'contract', label: 'Contract' },
  { value: 'temp', label: 'Temporary' },
];

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

  const [profile, setProfile] = useState<any>(null);
  const [details, setDetails] = useState<any>(null);
  const [profileLoading, setProfileLoading] = useState(true);

  // Job form
  const [showJobForm, setShowJobForm] = useState(false);
  const [jobTitle, setJobTitle] = useState('');
  const [jobCompany, setJobCompany] = useState('');
  const [jobLocation, setJobLocation] = useState('');
  const [jobType, setJobType] = useState('full_time');
  const [jobSalaryMin, setJobSalaryMin] = useState('');
  const [jobSalaryMax, setJobSalaryMax] = useState('');
  const [jobDescription, setJobDescription] = useState('');
  const [jobApplyUrl, setJobApplyUrl] = useState('');
  const [jobApplyEmail, setJobApplyEmail] = useState('');
  const [jobSubmitting, setJobSubmitting] = useState(false);
  const [jobMsg, setJobMsg] = useState('');

  // Gig form
  const [showGigForm, setShowGigForm] = useState(false);
  const [gigTitle, setGigTitle] = useState('');
  const [gigCompany, setGigCompany] = useState('');
  const [gigLocation, setGigLocation] = useState('');
  const [gigType, setGigType] = useState('');
  const [gigRate, setGigRate] = useState('');
  const [gigStartDate, setGigStartDate] = useState('');
  const [gigEndDate, setGigEndDate] = useState('');
  const [gigDescription, setGigDescription] = useState('');
  const [gigContact, setGigContact] = useState('');
  const [gigSubmitting, setGigSubmitting] = useState(false);
  const [gigMsg, setGigMsg] = useState('');

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

  useEffect(() => {
    if (!user) return;
    const fetchProfile = async () => {
      setProfileLoading(true);
      const { data: p } = await supabase
        .from('marketplace_profiles')
        .select('*')
        .eq('user_id', user.id)
        .maybeSingle();

      setProfile(p);

      if (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);
        }
      }
      setProfileLoading(false);
    };
    fetchProfile();
  }, [user, supabase]);

  const hasActiveSubscription =
    profile?.subscription_tier === 'pro' || profile?.subscription_tier === 'featured';

  const handlePostJob = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!profile) return;
    setJobSubmitting(true);
    setJobMsg('');
    try {
      const { error } = await supabase.from('marketplace_jobs').insert({
        profile_id: profile.id,
        title: jobTitle.trim(),
        company: jobCompany.trim(),
        location: jobLocation.trim(),
        job_type: jobType,
        salary_min: jobSalaryMin ? parseInt(jobSalaryMin) : null,
        salary_max: jobSalaryMax ? parseInt(jobSalaryMax) : null,
        description: jobDescription.trim(),
        apply_url: jobApplyUrl.trim() || null,
        apply_email: jobApplyEmail.trim() || null,
        status: 'active',
      });
      if (error) throw error;
      setJobMsg('✅ Job posted successfully!');
      setShowJobForm(false);
      setJobTitle(''); setJobCompany(''); setJobLocation('');
      setJobDescription(''); setJobApplyUrl(''); setJobApplyEmail('');
    } catch (err: any) {
      setJobMsg(`❌ ${err.message}`);
    } finally {
      setJobSubmitting(false);
    }
  };

  const handlePostGig = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!profile) return;
    setGigSubmitting(true);
    setGigMsg('');
    try {
      const { error } = await supabase.from('marketplace_gigs').insert({
        profile_id: profile.id,
        title: gigTitle.trim(),
        company: gigCompany.trim(),
        location: gigLocation.trim(),
        gig_type: gigType,
        rate: gigRate.trim() || null,
        start_date: gigStartDate || null,
        end_date: gigEndDate || null,
        description: gigDescription.trim(),
        contact_method: gigContact.trim() || null,
        status: 'active',
      });
      if (error) throw error;
      setGigMsg('✅ Gig posted successfully!');
      setShowGigForm(false);
      setGigTitle(''); setGigCompany(''); setGigLocation('');
      setGigDescription(''); setGigContact('');
    } catch (err: any) {
      setGigMsg(`❌ ${err.message}`);
    } finally {
      setGigSubmitting(false);
    }
  };

  if (loading || profileLoading) {
    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>
    );
  }

  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-6">
          <Link href="/marketplace" className="hover:text-[#CC0000]">
            Marketplace
          </Link>
          <span>/</span>
          <span className="text-white">My Account</span>
        </div>

        <h1 className="text-3xl font-black uppercase tracking-wide mb-8">My Account</h1>

        {/* No profile yet */}
        {!profile && (
          <div className="bg-[#FFFFFF] border border-white/10 rounded-xl p-8 text-center">
            <div className="text-4xl mb-4">👤</div>
            <h2 className="text-xl font-bold mb-3">No Profile Yet</h2>
            <p className="text-gray-400 mb-6">
              Create your marketplace profile to get discovered by clients and employers.
            </p>
            <Link
              href="/marketplace/join"
              className="bg-[#CC0000] hover:bg-red-700 text-white font-bold px-6 py-3 rounded-lg transition-colors"
            >
              Create Profile
            </Link>
          </div>
        )}

        {/* Profile status card */}
        {profile && (
          <div className="grid md:grid-cols-3 gap-6 mb-8">
            <div className="bg-[#FFFFFF] border border-white/10 rounded-xl p-6">
              <div className="text-xs text-gray-400 uppercase tracking-wide mb-1">Profile Status</div>
              <div
                className={`text-lg font-bold capitalize ${
                  profile.status === 'active' ?'text-green-400'
                    : profile.status === 'pending' ?'text-yellow-400' :'text-red-400'
                }`}
              >
                {profile.status === 'active' ?'✓ Active'
                  : profile.status === 'pending' ?'⏳ Pending Review' :'✗ Rejected'}
              </div>
              {profile.status === 'pending' && (
                <p className="text-xs text-gray-500 mt-2">
                  Our team will review your profile within 24 hours.
                </p>
              )}
              {profile.status === 'rejected' && profile.rejection_reason && (
                <p className="text-xs text-red-400 mt-2">{profile.rejection_reason}</p>
              )}
            </div>

            <div className="bg-[#FFFFFF] border border-white/10 rounded-xl p-6">
              <div className="text-xs text-gray-400 uppercase tracking-wide mb-1">Plan</div>
              <div className="text-lg font-bold capitalize text-white">
                {profile.subscription_tier === 'featured' ?'⭐ Featured'
                  : profile.subscription_tier === 'pro' ?'🚀 Pro' :'🆓 Free'}
              </div>
              <Link
                href="/marketplace/account/billing"
                className="text-xs text-[#CC0000] hover:underline mt-2 block"
              >
                Manage billing →
              </Link>
            </div>

            <div className="bg-[#FFFFFF] border border-white/10 rounded-xl p-6">
              <div className="text-xs text-gray-400 uppercase tracking-wide mb-1">Profile Type</div>
              <div className="text-lg font-bold capitalize text-white">
                {profile.profile_type === 'crew' ? '🎬 Crew Member' : '🏢 Vendor / Company'}
              </div>
              {profile.status === 'active' && (
                <Link
                  href={`/marketplace/profile/${profile.slug}`}
                  className="text-xs text-[#CC0000] hover:underline mt-2 block"
                >
                  View public profile →
                </Link>
              )}
            </div>
          </div>
        )}

        {/* Post Job / Gig section */}
        {profile && (
          <div className="space-y-6">
            <h2 className="text-xl font-bold">Post Listings</h2>

            {/* Subscription gate notice */}
            {!hasActiveSubscription && (
              <div className="bg-[#FFFFFF] border border-yellow-500/30 rounded-xl p-6">
                <div className="flex items-start gap-4">
                  <div className="text-2xl">💳</div>
                  <div>
                    <h3 className="font-bold text-yellow-400 mb-1">Pro Subscription Required</h3>
                    <p className="text-sm text-gray-400 mb-3">
                      Posting jobs and gigs requires an active Pro or Featured subscription.
                      Billing is coming soon — your profile is ready and waiting.
                    </p>
                    <Link
                      href="/marketplace/account/billing"
                      className="text-sm text-[#CC0000] hover:underline font-semibold"
                    >
                      View billing options →
                    </Link>
                  </div>
                </div>
              </div>
            )}

            {/* Job post form */}
            <div className="bg-[#FFFFFF] border border-white/10 rounded-xl overflow-hidden">
              <button
                onClick={() => setShowJobForm((p) => !p)}
                disabled={!hasActiveSubscription}
                className="w-full flex items-center justify-between p-6 text-left disabled:opacity-50"
              >
                <div>
                  <div className="font-bold text-lg">Post a Job</div>
                  <div className="text-sm text-gray-400">Full-time, part-time, or contract</div>
                </div>
                <span className="text-gray-400">{showJobForm ? '▲' : '▼'}</span>
              </button>

              {showJobForm && (
                <form onSubmit={handlePostJob} className="px-6 pb-6 space-y-4 border-t border-white/10 pt-6">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="col-span-2">
                      <label className="block text-xs text-gray-400 mb-1">Job Title *</label>
                      <input
                        value={jobTitle}
                        onChange={(e) => setJobTitle(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="e.g. Senior AV Integrator"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Company *</label>
                      <input
                        value={jobCompany}
                        onChange={(e) => setJobCompany(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Location *</label>
                      <input
                        value={jobLocation}
                        onChange={(e) => setJobLocation(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="City, State or Remote"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Job Type</label>
                      <select
                        value={jobType}
                        onChange={(e) => setJobType(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      >
                        {JOB_TYPES.map((t) => (
                          <option key={t.value} value={t.value}>
                            {t.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Salary Range</label>
                      <div className="flex gap-2">
                        <input
                          type="number"
                          value={jobSalaryMin}
                          onChange={(e) => setJobSalaryMin(e.target.value)}
                          className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                          placeholder="Min $"
                        />
                        <input
                          type="number"
                          value={jobSalaryMax}
                          onChange={(e) => setJobSalaryMax(e.target.value)}
                          className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                          placeholder="Max $"
                        />
                      </div>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-xs text-gray-400 mb-1">Description *</label>
                      <textarea
                        value={jobDescription}
                        onChange={(e) => setJobDescription(e.target.value)}
                        required
                        rows={5}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000] resize-none"
                        placeholder="Job description, requirements, responsibilities..."
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Apply URL</label>
                      <input
                        value={jobApplyUrl}
                        onChange={(e) => setJobApplyUrl(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="https://..."
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Apply Email</label>
                      <input
                        type="email"
                        value={jobApplyEmail}
                        onChange={(e) => setJobApplyEmail(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="jobs@company.com"
                      />
                    </div>
                  </div>
                  {jobMsg && (
                    <p
                      className={`text-sm px-4 py-2 rounded-lg ${
                        jobMsg.startsWith('✅')
                          ? 'bg-green-500/10 text-green-400' :'bg-red-500/10 text-red-400'
                      }`}
                    >
                      {jobMsg}
                    </p>
                  )}
                  <button
                    type="submit"
                    disabled={jobSubmitting}
                    className="bg-[#CC0000] hover:bg-red-700 disabled:opacity-50 text-white font-bold px-6 py-2.5 rounded-lg text-sm transition-colors"
                  >
                    {jobSubmitting ? 'Posting...' : 'Post Job'}
                  </button>
                </form>
              )}
            </div>

            {/* Gig post form */}
            <div className="bg-[#FFFFFF] border border-white/10 rounded-xl overflow-hidden">
              <button
                onClick={() => setShowGigForm((p) => !p)}
                disabled={!hasActiveSubscription}
                className="w-full flex items-center justify-between p-6 text-left disabled:opacity-50"
              >
                <div>
                  <div className="font-bold text-lg">Post a Gig</div>
                  <div className="text-sm text-gray-400">Short-term crew call or freelance request</div>
                </div>
                <span className="text-gray-400">{showGigForm ? '▲' : '▼'}</span>
              </button>

              {showGigForm && (
                <form onSubmit={handlePostGig} className="px-6 pb-6 space-y-4 border-t border-white/10 pt-6">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="col-span-2">
                      <label className="block text-xs text-gray-400 mb-1">Gig Title *</label>
                      <input
                        value={gigTitle}
                        onChange={(e) => setGigTitle(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="e.g. DP needed for 2-day commercial shoot"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Company / Production *</label>
                      <input
                        value={gigCompany}
                        onChange={(e) => setGigCompany(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Location *</label>
                      <input
                        value={gigLocation}
                        onChange={(e) => setGigLocation(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Project Type *</label>
                      <select
                        value={gigType}
                        onChange={(e) => setGigType(e.target.value)}
                        required
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      >
                        <option value="">Select type...</option>
                        {GIG_TYPES.map((t) => (
                          <option key={t} value={t}>
                            {t}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Rate</label>
                      <input
                        value={gigRate}
                        onChange={(e) => setGigRate(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="e.g. $750/day or negotiable"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Start Date</label>
                      <input
                        type="date"
                        value={gigStartDate}
                        onChange={(e) => setGigStartDate(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">End Date</label>
                      <input
                        type="date"
                        value={gigEndDate}
                        onChange={(e) => setGigEndDate(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                      />
                    </div>
                    <div className="col-span-2">
                      <label className="block text-xs text-gray-400 mb-1">Description *</label>
                      <textarea
                        value={gigDescription}
                        onChange={(e) => setGigDescription(e.target.value)}
                        required
                        rows={4}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000] resize-none"
                        placeholder="Project details, crew needed, requirements..."
                      />
                    </div>
                    <div className="col-span-2">
                      <label className="block text-xs text-gray-400 mb-1">How to Respond</label>
                      <input
                        value={gigContact}
                        onChange={(e) => setGigContact(e.target.value)}
                        className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="Email address, phone, or instructions"
                      />
                    </div>
                  </div>
                  {gigMsg && (
                    <p
                      className={`text-sm px-4 py-2 rounded-lg ${
                        gigMsg.startsWith('✅')
                          ? 'bg-green-500/10 text-green-400' :'bg-red-500/10 text-red-400'
                      }`}
                    >
                      {gigMsg}
                    </p>
                  )}
                  <button
                    type="submit"
                    disabled={gigSubmitting}
                    className="bg-[#CC0000] hover:bg-red-700 disabled:opacity-50 text-white font-bold px-6 py-2.5 rounded-lg text-sm transition-colors"
                  >
                    {gigSubmitting ? 'Posting...' : 'Post Gig'}
                  </button>
                </form>
              )}
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}
