'use client';

import { useState } 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';

const SKILL_OPTIONS = [
  'Director of Photography',
  'Camera Operator',
  '1st AC / Focus Puller',
  'DIT',
  'Steadicam Operator',
  'Drone / UAV Operator',
  'Gaffer',
  'Grip / Key Grip',
  'Production Sound Mixer',
  'Boom Operator',
  'Sound Designer',
  'Audio Post / Mixing Engineer',
  'Director',
  'Producer',
  'Line Producer',
  'Production Manager',
  'Assistant Director',
  'Script Supervisor',
  'Editor (Offline)',
  'Online Editor / Finishing',
  'Colorist',
  'Motion Graphics Designer',
  'VFX Artist / Compositor',
  'Animator (2D/3D)',
  'Technical Director',
  'Broadcast Engineer',
  'Master Control Operator',
  'Graphics Operator',
  'Live Event Producer',
  'Livestream Producer',
  'Social Media Video Producer',
  'Photographer',
];

const VENDOR_CATEGORIES = [
  'Full-Service Production Company',
  'Equipment Rental House',
  'Studio / Stage Rental',
  'Post Production Facility',
  'Animation Studio',
  'Drone Services Company',
  'Casting Agency',
  'Talent Agency',
  'Production Insurance',
  'Catering / Craft Services',
  'Transportation / Vehicles',
  'Other',
];

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');
}

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

  const [step, setStep] = useState<'type' | 'details' | 'submitting' | 'done'>('type');
  const [profileType, setProfileType] = useState<'crew' | 'vendor' | null>(null);
  const [error, setError] = useState('');
  const [uploading, setUploading] = useState(false);

  // Auth state
  const [authMode, setAuthMode] = useState<'login' | 'signup'>('signup');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [authError, setAuthError] = useState('');
  const [authLoading, setAuthLoading] = useState(false);

  // Crew fields
  const [crewName, setCrewName] = useState('');
  const [crewLocation, setCrewLocation] = useState('');
  const [crewUnion, setCrewUnion] = useState('non_union');
  const [crewRate, setCrewRate] = useState('');
  const [crewBio, setCrewBio] = useState('');
  const [crewSkills, setCrewSkills] = useState<string[]>([]);
  const [crewEquipment, setCrewEquipment] = useState('');
  const [crewReel, setCrewReel] = useState('');
  const [headshotFile, setHeadshotFile] = useState<File | null>(null);
  const [resumeFile, setResumeFile] = useState<File | null>(null);

  // Vendor fields
  const [vendorName, setVendorName] = useState('');
  const [vendorLocation, setVendorLocation] = useState('');
  const [vendorCategory, setVendorCategory] = useState('');
  const [vendorDescription, setVendorDescription] = useState('');
  const [vendorWebsite, setVendorWebsite] = useState('');
  const [vendorEmail, setVendorEmail] = useState('');
  const [logoFile, setLogoFile] = useState<File | null>(null);

  const handleAuth = async (e: React.FormEvent) => {
    e.preventDefault();
    setAuthLoading(true);
    setAuthError('');
    try {
      if (authMode === 'signup') {
        const { error } = await supabase.auth.signUp({ email, password });
        if (error) throw error;
      } else {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
      }
    } catch (err: any) {
      setAuthError(err.message);
    } finally {
      setAuthLoading(false);
    }
  };

  const toggleSkill = (skill: string) => {
    setCrewSkills((prev) =>
      prev.includes(skill) ? prev.filter((s) => s !== skill) : [...prev, skill]
    );
  };

  const uploadFile = async (
    file: File,
    bucket: string,
    userId: string
  ): Promise<string | null> => {
    const ext = file.name.split('.').pop();
    const path = `${userId}/${Date.now()}.${ext}`;
    const { error } = await supabase.storage.from(bucket).upload(path, file, { upsert: true });
    if (error) return null;
    if (bucket === 'marketplace-resumes') return path;
    const { data } = supabase.storage.from(bucket).getPublicUrl(path);
    return data.publicUrl;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user) return;
    setError('');
    setStep('submitting');
    setUploading(true);

    try {
      let headshotUrl: string | null = null;
      let logoUrl: string | null = null;
      let resumeUrl: string | null = null;

      if (profileType === 'crew') {
        if (!crewName.trim() || !crewLocation.trim()) {
          setError('Name and location are required.');
          setStep('details');
          return;
        }
        if (headshotFile) {
          headshotUrl = await uploadFile(headshotFile, 'marketplace-headshots', user.id);
        }
        if (resumeFile) {
          resumeUrl = await uploadFile(resumeFile, 'marketplace-resumes', user.id);
        }
      } else {
        if (!vendorName.trim() || !vendorLocation.trim() || !vendorCategory) {
          setError('Company name, location, and category are required.');
          setStep('details');
          return;
        }
        if (logoFile) {
          logoUrl = await uploadFile(logoFile, 'marketplace-logos', user.id);
        }
      }

      const baseSlug = slugify(
        profileType === 'crew' ? crewName : vendorName
      );
      const slug = `${baseSlug}-${Date.now().toString(36)}`;

      // Create profile record
      const { data: profile, error: profileError } = await supabase
        .from('marketplace_profiles')
        .insert({
          user_id: user.id,
          profile_type: profileType,
          slug,
          status: 'pending',
          subscription_tier: 'free',
        })
        .select()
        .single();

      if (profileError) throw profileError;

      // Create detail record
      if (profileType === 'crew') {
        const { error: detailError } = await supabase
          .from('marketplace_crew_details')
          .insert({
            profile_id: profile.id,
            name: crewName.trim(),
            headshot_url: headshotUrl,
            location: crewLocation.trim(),
            union_status: crewUnion,
            day_rate: crewRate ? parseInt(crewRate) : null,
            bio: crewBio.trim(),
            skills: crewSkills,
            equipment: crewEquipment
              ? crewEquipment.split(',').map((s) => s.trim()).filter(Boolean)
              : [],
            reel_url: crewReel.trim() || null,
            resume_url: resumeUrl,
          });
        if (detailError) throw detailError;
      } else {
        const { error: detailError } = await supabase
          .from('marketplace_vendor_details')
          .insert({
            profile_id: profile.id,
            company_name: vendorName.trim(),
            logo_url: logoUrl,
            location: vendorLocation.trim(),
            category: vendorCategory,
            description: vendorDescription.trim(),
            website: vendorWebsite.trim() || null,
            contact_email: vendorEmail.trim() || user.email,
          });
        if (detailError) throw detailError;
      }

      setStep('done');
    } catch (err: any) {
      setError(err.message || 'Something went wrong. Please try again.');
      setStep('details');
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC] text-white">
      <Header />
      <div className="max-w-2xl mx-auto px-4 py-24">
        {/* Header */}
        <div className="text-center mb-10">
          <Link href="/marketplace" className="text-[#CC0000] text-sm hover:underline">
            ← Back to Marketplace
          </Link>
          <h1 className="text-3xl font-black uppercase tracking-wide mt-4 mb-2">
            Join the Marketplace
          </h1>
          <p className="text-gray-400">
            Create your free profile and get discovered by clients and employers.
          </p>
        </div>

        {/* Auth gate */}
        {!user && (
          <div className="bg-[#FFFFFF] border border-white/10 rounded-xl p-8 mb-8">
            <h2 className="text-lg font-bold mb-6 text-center">
              {authMode === 'signup' ? 'Create an Account' : 'Sign In to Continue'}
            </h2>
            <form onSubmit={handleAuth} className="space-y-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Email</label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="you@example.com"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Password</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength={6}
                  className="w-full bg-[#F8FAFC] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="••••••••"
                />
              </div>
              {authError && (
                <p className="text-red-400 text-sm bg-red-400/10 rounded-lg px-4 py-2">
                  {authError}
                </p>
              )}
              <button
                type="submit"
                disabled={authLoading}
                className="w-full bg-[#CC0000] hover:bg-red-700 disabled:opacity-50 text-white font-bold py-3 rounded-lg transition-colors"
              >
                {authLoading
                  ? 'Please wait...'
                  : authMode === 'signup' ?'Create Account' :'Sign In'}
              </button>
            </form>
            <p className="text-center text-sm text-gray-500 mt-4">
              {authMode === 'signup' ? 'Already have an account?' : "Don't have an account?"}{' '}
              <button
                onClick={() => setAuthMode(authMode === 'signup' ? 'login' : 'signup')}
                className="text-[#CC0000] hover:underline"
              >
                {authMode === 'signup' ? 'Sign in' : 'Sign up'}
              </button>
            </p>
          </div>
        )}

        {/* Step: Choose type */}
        {user && step === 'type' && (
          <div className="space-y-4">
            <h2 className="text-lg font-bold text-center mb-6">What type of profile?</h2>
            <button
              onClick={() => {
                setProfileType('crew');
                setStep('details');
              }}
              className="w-full bg-[#FFFFFF] hover:bg-[#222] border border-white/10 hover:border-[#CC0000]/50 rounded-xl p-6 text-left transition-all group"
            >
              <div className="text-2xl mb-2">🎬</div>
              <div className="font-bold text-lg group-hover:text-[#CC0000] transition-colors">
                Crew Member / Freelancer
              </div>
              <div className="text-sm text-gray-400 mt-1">
                DP, Editor, Sound Mixer, Colorist, Engineer, and more
              </div>
            </button>
            <button
              onClick={() => {
                setProfileType('vendor');
                setStep('details');
              }}
              className="w-full bg-[#FFFFFF] hover:bg-[#222] border border-white/10 hover:border-[#CC0000]/50 rounded-xl p-6 text-left transition-all group"
            >
              <div className="text-2xl mb-2">🏢</div>
              <div className="font-bold text-lg group-hover:text-[#CC0000] transition-colors">
                Vendor / Company
              </div>
              <div className="text-sm text-gray-400 mt-1">
                Production company, rental house, post facility, studio
              </div>
            </button>
          </div>
        )}

        {/* Step: Crew details */}
        {user && step === 'details' && profileType === 'crew' && (
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="flex items-center gap-3 mb-6">
              <button
                type="button"
                onClick={() => setStep('type')}
                className="text-gray-400 hover:text-white text-sm"
              >
                ← Back
              </button>
              <h2 className="text-lg font-bold">Crew Member Profile</h2>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2">
                <label className="block text-sm text-gray-400 mb-1">
                  Full Name <span className="text-[#CC0000]">*</span>
                </label>
                <input
                  value={crewName}
                  onChange={(e) => setCrewName(e.target.value)}
                  required
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="Your professional name"
                />
              </div>
              <div className="col-span-2">
                <label className="block text-sm text-gray-400 mb-1">
                  Location <span className="text-[#CC0000]">*</span>
                </label>
                <input
                  value={crewLocation}
                  onChange={(e) => setCrewLocation(e.target.value)}
                  required
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="City, State / Country"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Union Status</label>
                <select
                  value={crewUnion}
                  onChange={(e) => setCrewUnion(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                >
                  <option value="non_union">Non-Union</option>
                  <option value="iatse">IATSE</option>
                  <option value="sag_aftra">SAG-AFTRA</option>
                  <option value="teamsters">Teamsters</option>
                  <option value="nabet">NABET</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Day Rate (USD)</label>
                <input
                  type="number"
                  value={crewRate}
                  onChange={(e) => setCrewRate(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="e.g. 750"
                  min="0"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">Bio / About</label>
              <textarea
                value={crewBio}
                onChange={(e) => setCrewBio(e.target.value)}
                rows={4}
                maxLength={500}
                className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000] resize-none"
                placeholder="Brief professional bio (500 chars max)"
              />
              <div className="text-xs text-gray-500 text-right mt-1">{crewBio.length}/500</div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-2">Skills / Specialties</label>
              <div className="flex flex-wrap gap-2">
                {SKILL_OPTIONS.map((skill) => (
                  <button
                    key={skill}
                    type="button"
                    onClick={() => toggleSkill(skill)}
                    className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
                      crewSkills.includes(skill)
                        ? 'bg-[#CC0000] border-[#CC0000] text-white'
                        : 'bg-transparent border-white/20 text-gray-400 hover:border-white/40'
                    }`}
                  >
                    {skill}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">Equipment Owned</label>
              <input
                value={crewEquipment}
                onChange={(e) => setCrewEquipment(e.target.value)}
                className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                placeholder="e.g. Sony FX9, DJI Ronin, Sennheiser MKH416 (comma-separated)"
              />
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">Reel / Demo URL</label>
              <input
                value={crewReel}
                onChange={(e) => setCrewReel(e.target.value)}
                className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                placeholder="https://vimeo.com/..."
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Headshot / Photo</label>
                <input
                  type="file"
                  accept="image/jpeg,image/jpg,image/png,image/webp"
                  onChange={(e) => setHeadshotFile(e.target.files?.[0] || null)}
                  className="w-full text-sm text-gray-400 file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-[#CC0000] file:text-white file:cursor-pointer"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Resume / CV (PDF)</label>
                <input
                  type="file"
                  accept="application/pdf,.doc,.docx"
                  onChange={(e) => setResumeFile(e.target.files?.[0] || null)}
                  className="w-full text-sm text-gray-400 file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-[#FFFFFF] file:border file:border-white/20 file:text-white file:cursor-pointer"
                />
              </div>
            </div>

            {error && (
              <p className="text-red-400 text-sm bg-red-400/10 rounded-lg px-4 py-2">{error}</p>
            )}

            <button
              type="submit"
              disabled={uploading}
              className="w-full bg-[#CC0000] hover:bg-red-700 disabled:opacity-50 text-white font-bold py-4 rounded-lg text-lg transition-colors"
            >
              {uploading ? 'Submitting...' : 'Submit Profile for Review'}
            </button>
            <p className="text-xs text-gray-500 text-center">
              All profiles are reviewed by our team before going live. Typically within 24 hours.
            </p>
          </form>
        )}

        {/* Step: Vendor details */}
        {user && step === 'details' && profileType === 'vendor' && (
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="flex items-center gap-3 mb-6">
              <button
                type="button"
                onClick={() => setStep('type')}
                className="text-gray-400 hover:text-white text-sm"
              >
                ← Back
              </button>
              <h2 className="text-lg font-bold">Vendor / Company Profile</h2>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">
                Company Name <span className="text-[#CC0000]">*</span>
              </label>
              <input
                value={vendorName}
                onChange={(e) => setVendorName(e.target.value)}
                required
                className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                placeholder="Your company name"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">
                  Location <span className="text-[#CC0000]">*</span>
                </label>
                <input
                  value={vendorLocation}
                  onChange={(e) => setVendorLocation(e.target.value)}
                  required
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="City, State / Country"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">
                  Category <span className="text-[#CC0000]">*</span>
                </label>
                <select
                  value={vendorCategory}
                  onChange={(e) => setVendorCategory(e.target.value)}
                  required
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                >
                  <option value="">Select category...</option>
                  {VENDOR_CATEGORIES.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">Company Description</label>
              <textarea
                value={vendorDescription}
                onChange={(e) => setVendorDescription(e.target.value)}
                rows={4}
                maxLength={1000}
                className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000] resize-none"
                placeholder="Describe your services, specialties, and what makes you stand out"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Website</label>
                <input
                  value={vendorWebsite}
                  onChange={(e) => setVendorWebsite(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="https://yourcompany.com"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Contact Email</label>
                <input
                  type="email"
                  value={vendorEmail}
                  onChange={(e) => setVendorEmail(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-[#CC0000]"
                  placeholder="contact@yourcompany.com"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-1">Company Logo</label>
              <input
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/webp,image/svg+xml"
                onChange={(e) => setLogoFile(e.target.files?.[0] || null)}
                className="w-full text-sm text-gray-400 file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-[#CC0000] file:text-white file:cursor-pointer"
              />
            </div>

            {error && (
              <p className="text-red-400 text-sm bg-red-400/10 rounded-lg px-4 py-2">{error}</p>
            )}

            <button
              type="submit"
              disabled={uploading}
              className="w-full bg-[#CC0000] hover:bg-red-700 disabled:opacity-50 text-white font-bold py-4 rounded-lg text-lg transition-colors"
            >
              {uploading ? 'Submitting...' : 'Submit Profile for Review'}
            </button>
            <p className="text-xs text-gray-500 text-center">
              All profiles are reviewed by our team before going live. Typically within 24 hours.
            </p>
          </form>
        )}

        {/* Submitting */}
        {step === 'submitting' && (
          <div className="text-center py-16">
            <div className="w-12 h-12 border-4 border-[#CC0000] border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-gray-400">Uploading your profile...</p>
          </div>
        )}

        {/* Done */}
        {step === 'done' && (
          <div className="text-center py-16">
            <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-6 text-3xl">
              ✓
            </div>
            <h2 className="text-2xl font-bold mb-3">Profile Submitted!</h2>
            <p className="text-gray-400 mb-8 max-w-md mx-auto">
              Your profile is now in our review queue. Our team will review it within 24 hours.
              You&apos;ll receive an email once it&apos;s approved and live.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Link
                href="/marketplace/account"
                className="bg-[#CC0000] hover:bg-red-700 text-white font-bold px-6 py-3 rounded-lg transition-colors"
              >
                View My Account
              </Link>
              <Link
                href="/marketplace"
                className="bg-white/10 hover:bg-white/20 text-white font-bold px-6 py-3 rounded-lg transition-colors"
              >
                Back to Marketplace
              </Link>
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}
