'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Briefcase,
  CheckCircle2,
  ExternalLink,
  FolderOpen,
  Loader2,
  MapPin,
  ShieldCheck,
  Sparkles,
  UserRound,
  Wallet,
} from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { SkillPicker, hasWorkerSkillSelection } from '@/components/workers/SkillPicker';
import { ServiceAreaPicker } from '@/components/map/LocationPicker';
import { WorkerProfileBadges, WorkerAvatar } from '@/components/workers/WorkerProfileDisplay';
import { ProfilePhotoPicker } from '@/components/ui/ProfilePhotoPicker';
import { GenderSelect } from '@/components/ui/GenderSelect';
import { api, getUploadUrl } from '@/lib/api';
import type { Gender } from '@ehandyhire/shared';
import { removeAvatar, uploadAvatar } from '@/lib/avatar';
import { WorkerRatePicker } from '@/components/workers/WorkerRatePicker';
import { WorkerPortalShell } from '@/components/worker/WorkerPortal';
import { AccountDeletionCard } from '@/components/account/AccountDeletionCard';
import { formatWorkerRate, type RateType } from '@/lib/rateType';
import { cn } from '@/lib/utils';
import type { ServiceAreaKey } from '@/lib/geocode';
import { normalizeWorkerServiceAreas } from '@/lib/geocode';

interface WorkerSkill {
  categoryId: string;
  category: { id: string; name: string; slug: string; icon?: string };
}

interface WorkerProfile {
  id?: string;
  displayName?: string | null;
  headline?: string;
  bio?: string;
  experienceYears?: number;
  hourlyRate?: string | number;
  rateType?: RateType;
  isAvailable?: boolean;
  isHired?: boolean;
  isVerified?: boolean;
  otherSkills?: string | null;
  isStudent?: boolean;
  skills?: WorkerSkill[];
  serviceAreas?: { area: ServiceAreaKey }[];
}

type ProfileSectionId = 'photo' | 'about' | 'rates' | 'skills' | 'areas';

const PROFILE_TABS: { id: ProfileSectionId; label: string; icon: typeof UserRound }[] = [
  { id: 'photo', label: 'Photo', icon: UserRound },
  { id: 'about', label: 'About', icon: Sparkles },
  { id: 'rates', label: 'Rates', icon: Wallet },
  { id: 'skills', label: 'Skills', icon: Briefcase },
  { id: 'areas', label: 'Areas', icon: MapPin },
];

export default function WorkerProfilePage() {
  const { user, refreshUser } = useAuth();
  const profile = user?.workerProfile as WorkerProfile | undefined;

  const [headline, setHeadline] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [useRealNameAsDisplay, setUseRealNameAsDisplay] = useState(false);
  const [bio, setBio] = useState('');
  const [experienceYears, setExperienceYears] = useState('');
  const [hourlyRate, setHourlyRate] = useState('');
  const [rateType, setRateType] = useState<RateType>('HOURLY');
  const [isAvailable, setIsAvailable] = useState(true);
  const [categoryIds, setCategoryIds] = useState<string[]>([]);
  const [otherSkills, setOtherSkills] = useState('');
  const [isStudent, setIsStudent] = useState(false);
  const [gender, setGender] = useState('');
  const [serviceAreas, setServiceAreas] = useState<ServiceAreaKey[]>(['DAVAO_CITY']);
  const [skillError, setSkillError] = useState('');
  const [otherSkillsError, setOtherSkillsError] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [initialized, setInitialized] = useState(false);
  const [activeSection, setActiveSection] = useState<ProfileSectionId>('about');

  useEffect(() => {
    void refreshUser();
  }, [refreshUser]);

  useEffect(() => {
    if (!profile || initialized) return;
    setGender(user?.gender ?? '');
    setDisplayName(profile.displayName || '');
    const legalName = `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim();
    setUseRealNameAsDisplay(
      Boolean(legalName) &&
        (profile.displayName || '').trim().toLowerCase() === legalName.toLowerCase()
    );
    setHeadline(profile.headline || '');
    setBio(profile.bio || '');
    setExperienceYears(String(profile.experienceYears ?? 0));
    setHourlyRate(profile.hourlyRate ? String(profile.hourlyRate) : '');
    setRateType((profile.rateType as RateType) || 'HOURLY');
    setIsAvailable(profile.isAvailable ?? true);
    setOtherSkills(profile.otherSkills || '');
    setIsStudent(profile.isStudent ?? false);
    setCategoryIds(
      profile.skills
        ?.filter((s) => s.category.slug !== 'other')
        .map((s) => s.categoryId) || []
    );
    setServiceAreas(
      normalizeWorkerServiceAreas(
        profile.serviceAreas?.length
          ? profile.serviceAreas.map((a) => a.area)
          : ['DAVAO_CITY']
      )
    );
    setInitialized(true);
  }, [profile, user, initialized]);

  const handleAvatarChange = async (file: File | null, previewUrl: string | null) => {
    if (!file && !user?.avatarUrl) {
      setAvatarPreview(null);
      return;
    }

    setAvatarPreview(previewUrl);
    setAvatarUploading(true);
    setError('');

    try {
      if (file) {
        const res = await uploadAvatar(file);
        await refreshUser();
        if (res.data.avatarUrl) {
          setAvatarPreview(getUploadUrl(res.data.avatarUrl));
        }
      } else {
        await removeAvatar();
        await refreshUser();
        setAvatarPreview(null);
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update profile photo');
    } finally {
      setAvatarUploading(false);
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSkillError('');
    setOtherSkillsError('');

    if (!hasWorkerSkillSelection(categoryIds, otherSkills)) {
      setSkillError('Select at least one skill or describe your skill under "Skill not listed?"');
      setActiveSection('skills');
      return;
    }
    if (otherSkills.trim() && otherSkills.trim().length < 2) {
      setOtherSkillsError('Please describe your skill in a few words');
      setActiveSection('skills');
      return;
    }

    if (!displayName.trim() || displayName.trim().length < 2) {
      setError('Display name is required (at least 2 characters)');
      setActiveSection('about');
      return;
    }

    setError('');
    setSuccess(false);
    setLoading(true);

    try {
      await api('/users/worker/profile', {
        method: 'PATCH',
        body: JSON.stringify({
          displayName: displayName.trim(),
          headline: headline.trim() || undefined,
          bio: bio.trim() || undefined,
          experienceYears: parseInt(experienceYears, 10) || 0,
          hourlyRate: hourlyRate ? parseFloat(hourlyRate) : undefined,
          rateType: hourlyRate ? rateType : undefined,
          isAvailable,
          otherSkills: otherSkills.trim() || undefined,
          isStudent,
          categoryIds,
          serviceAreas,
        }),
      });
      await api('/users/profile', {
        method: 'PATCH',
        body: JSON.stringify({
          gender: gender ? (gender as Gender) : null,
        }),
      });
      await refreshUser();
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to save profile');
    } finally {
      setLoading(false);
    }
  };

  const publicProfileHref = profile?.id ? `/workers/${profile.id}` : null;
  const displayAvatarUrl =
    avatarPreview ?? (user?.avatarUrl ? getUploadUrl(user.avatarUrl) : null);
  const rateLabel = hourlyRate ? formatWorkerRate(hourlyRate, rateType) : null;
  const isHired = profile?.isHired === true;
  const shownName = displayName.trim() || `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim();

  const availabilityLabel = isHired
    ? 'Hired'
    : isAvailable
      ? 'Available'
      : 'Unavailable';

  return (
    <DashboardLayout role="worker" title="Profile">
      <WorkerPortalShell>
        {/* Compact summary — same visual height language as Availability / Notifications */}
        <section className="border border-[#e2ddd2] bg-[#fffdf9]">
          <div className="flex flex-col gap-4 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-5">
            <div className="flex min-w-0 items-start gap-3.5">
              <WorkerAvatar
                user={{
                  firstName: user?.firstName ?? '',
                  lastName: user?.lastName ?? '',
                  avatarUrl: displayAvatarUrl,
                }}
                size="sm"
                rounded="none"
                className="ring-1 ring-[#e2ddd2]"
              />
              <div className="min-w-0">
                <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--home-amber)]">
                  Your profile
                </p>
                <div className="mt-0.5 flex flex-wrap items-center gap-2">
                  <h2 className="home-display truncate text-2xl font-bold text-[var(--home-ink)]">
                    {shownName || 'Worker'}
                  </h2>
                  <WorkerProfileBadges
                    isVerified={profile?.isVerified}
                    isStudent={isStudent}
                  />
                </div>
                <p className="mt-1 truncate text-sm text-muted">
                  {headline || user?.email || user?.phone || 'Complete your profile details below'}
                </p>
                <div className="mt-2 flex flex-wrap gap-1.5">
                  <span
                    className={cn(
                      'px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white',
                      isHired
                        ? 'bg-rose-600'
                        : isAvailable
                          ? 'bg-[var(--home-amber)]'
                          : 'bg-slate-500'
                    )}
                  >
                    {availabilityLabel}
                  </span>
                  {rateLabel ? (
                    <span className="border border-[#e2ddd2] bg-white px-2 py-0.5 text-[10px] font-semibold text-slate-700">
                      {rateLabel}
                    </span>
                  ) : null}
                  {experienceYears && Number(experienceYears) > 0 ? (
                    <span className="border border-[#e2ddd2] bg-white px-2 py-0.5 text-[10px] font-semibold text-slate-700">
                      {experienceYears} yrs exp.
                    </span>
                  ) : null}
                </div>
              </div>
            </div>

            <div className="flex shrink-0 flex-wrap gap-2 sm:flex-col sm:items-stretch">
              {publicProfileHref ? (
                <Link href={publicProfileHref}>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="w-full gap-1.5 rounded-none"
                  >
                    <ExternalLink className="h-4 w-4" />
                    Public profile
                  </Button>
                </Link>
              ) : null}
              <Link href="/worker/portfolio">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="w-full gap-1.5 rounded-none"
                >
                  <FolderOpen className="h-4 w-4" />
                  Portfolio
                </Button>
              </Link>
            </div>
          </div>
        </section>

        {!profile?.isVerified ? (
          <section className="flex flex-col gap-3 border border-amber-200 bg-amber-50 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
            <div className="flex items-start gap-3">
              <ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-amber-600" />
              <div>
                <p className="font-semibold text-[var(--home-ink)]">
                  Not visible to customers yet
                </p>
                <p className="mt-0.5 text-sm text-muted">
                  Keep editing — your public profile stays hidden until verification is approved.
                </p>
              </div>
            </div>
            <Link href="/worker/verification">
              <Button size="sm" variant="accent" className="rounded-none">
                Go to verification
              </Button>
            </Link>
          </section>
        ) : null}

        <form onSubmit={handleSave} className="space-y-4">
          {/* Section tabs */}
          <div className="border border-[#e2ddd2] bg-[#fffdf9]">
            <div className="flex gap-0 overflow-x-auto border-b border-[#e2ddd2] scrollbar-none">
              {PROFILE_TABS.map((tab) => {
                const active = activeSection === tab.id;
                const Icon = tab.icon;
                return (
                  <button
                    key={tab.id}
                    type="button"
                    role="tab"
                    aria-selected={active}
                    onClick={() => setActiveSection(tab.id)}
                    className={cn(
                      'relative flex shrink-0 items-center gap-1.5 px-3.5 py-3 text-sm font-semibold transition-colors sm:px-4',
                      active
                        ? 'bg-white text-[var(--home-ink)]'
                        : 'text-muted hover:bg-white/70 hover:text-slate-800'
                    )}
                  >
                    <Icon className="h-4 w-4 shrink-0" />
                    {tab.label}
                    {active ? (
                      <span className="absolute inset-x-0 bottom-0 h-0.5 bg-[var(--home-amber)]" />
                    ) : null}
                  </button>
                );
              })}
            </div>

            <div className="bg-white p-4 sm:p-5" role="tabpanel">
              {activeSection === 'photo' ? (
                <div className="space-y-3">
                  <div>
                    <h3 className="font-bold text-[var(--home-ink)]">Profile photo</h3>
                    <p className="mt-1 text-sm text-muted">
                      Shown on your public profile, search cards, and messages.
                    </p>
                  </div>
                  <ProfilePhotoPicker
                    previewUrl={displayAvatarUrl}
                    onChange={handleAvatarChange}
                    firstName={user?.firstName}
                    lastName={user?.lastName}
                    disabled={avatarUploading}
                    helperText={
                      avatarUploading
                        ? 'Uploading profile photo…'
                        : 'Upload or take a photo customers will recognize.'
                    }
                    pendingLabel={avatarUploading ? 'Uploading…' : undefined}
                    className="!space-y-2"
                  />
                </div>
              ) : null}

              {activeSection === 'about' ? (
                <div className="space-y-4">
                  <div>
                    <h3 className="font-bold text-[var(--home-ink)]">About you</h3>
                    <p className="mt-1 text-sm text-muted">
                      How customers see you in search and on your public profile.
                    </p>
                  </div>
                  <div className="space-y-1.5">
                    <Input
                      label="Display name"
                      value={displayName}
                      onChange={(e) => {
                        setUseRealNameAsDisplay(false);
                        setDisplayName(e.target.value);
                      }}
                      placeholder="e.g. Mang Pedro, Ate Rosa"
                      maxLength={60}
                      required
                      readOnly={useRealNameAsDisplay}
                    />
                    <label className="flex cursor-pointer select-none items-start gap-2.5">
                      <input
                        type="checkbox"
                        checked={useRealNameAsDisplay}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          setUseRealNameAsDisplay(checked);
                          if (checked) {
                            setDisplayName(
                              `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim()
                            );
                          }
                        }}
                        disabled={!`${user?.firstName ?? ''}${user?.lastName ?? ''}`.trim()}
                        className="mt-0.5 h-4 w-4 shrink-0 border-[#d6d0c4] text-[var(--home-amber)] focus:ring-[var(--home-amber)]/30 disabled:opacity-50"
                      />
                      <span className="text-sm leading-snug text-slate-700">
                        Use my real first and last name
                      </span>
                    </label>
                    <p className="text-xs text-muted">
                      Shown publicly — choose a clear, professional name customers will trust.
                    </p>
                  </div>
                  <Input
                    label="Headline"
                    value={headline}
                    onChange={(e) => setHeadline(e.target.value)}
                    placeholder="e.g. Licensed electrician — 10 years experience"
                    maxLength={200}
                  />
                  <div className="space-y-1.5">
                    <label htmlFor="bio" className="text-sm font-medium text-slate-700">
                      Bio
                    </label>
                    <textarea
                      id="bio"
                      value={bio}
                      onChange={(e) => setBio(e.target.value)}
                      placeholder="Tell customers about your experience, specialties, and what jobs you take on..."
                      rows={4}
                      maxLength={2000}
                      className="search-input min-h-[88px] w-full resize-y py-2.5"
                    />
                  </div>
                  <div className="grid gap-4 sm:grid-cols-2">
                    <Input
                      label="Years of experience"
                      type="number"
                      min={0}
                      value={experienceYears}
                      onChange={(e) => setExperienceYears(e.target.value)}
                    />
                    <GenderSelect
                      value={gender}
                      onChange={setGender}
                      required
                      helperText="For customer search filters only — not shown publicly."
                    />
                  </div>
                </div>
              ) : null}

              {activeSection === 'rates' ? (
                <div className="space-y-4">
                  <div>
                    <h3 className="font-bold text-[var(--home-ink)]">Rates</h3>
                    <p className="mt-1 text-sm text-muted">
                      Set your typical rate. Manage open/closed status on Availability.
                    </p>
                  </div>
                  <WorkerRatePicker
                    amount={hourlyRate}
                    rateType={rateType}
                    onAmountChange={setHourlyRate}
                    onRateTypeChange={setRateType}
                    optional
                  />
                  <div className="flex flex-col gap-3 border border-[#e2ddd2] bg-[var(--home-sand)]/40 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                      <p className="text-sm font-semibold text-[var(--home-ink)]">
                        Status: {availabilityLabel}
                      </p>
                      <p className="mt-0.5 text-xs text-muted">
                        Customers see this badge on your public profile.
                      </p>
                    </div>
                    <Link href="/worker/availability">
                      <Button type="button" size="sm" variant="outline" className="rounded-none">
                        Manage availability
                      </Button>
                    </Link>
                  </div>
                </div>
              ) : null}

              {activeSection === 'skills' ? (
                <div className="space-y-4">
                  <div>
                    <h3 className="font-bold text-[var(--home-ink)]">Skills & trades</h3>
                    <p className="mt-1 text-sm text-muted">
                      Categories you work in, plus any custom skill.
                    </p>
                  </div>
                  <SkillPicker
                    value={categoryIds}
                    onChange={(ids) => {
                      setCategoryIds(ids);
                      if (ids.length > 0 || otherSkills.trim()) setSkillError('');
                    }}
                    otherSkills={otherSkills}
                    onOtherSkillsChange={(value) => {
                      setOtherSkills(value);
                      if (otherSkillsError) setOtherSkillsError('');
                      if (value.trim() || categoryIds.length > 0) setSkillError('');
                    }}
                    isStudent={isStudent}
                    onIsStudentChange={setIsStudent}
                    error={skillError}
                    otherSkillsError={otherSkillsError}
                  />
                </div>
              ) : null}

              {activeSection === 'areas' ? (
                <div className="space-y-4">
                  <div>
                    <h3 className="font-bold text-[var(--home-ink)]">Service areas</h3>
                    <p className="mt-1 text-sm text-muted">
                      Where you work — affects directory filters and your map pin.
                    </p>
                  </div>
                  <ServiceAreaPicker value={serviceAreas} onChange={setServiceAreas} />
                </div>
              ) : null}
            </div>
          </div>

          {/* Save bar */}
          <div className="sticky bottom-4 z-20 border border-[#e2ddd2] bg-[#fffdf9]/95 shadow-md backdrop-blur supports-[backdrop-filter]:bg-[#fffdf9]/90">
            <div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between">
              <div className="min-w-0">
                {error ? <p className="text-sm text-red-600">{error}</p> : null}
                {success ? (
                  <p className="flex items-center gap-1.5 text-sm font-medium text-emerald-700">
                    <CheckCircle2 className="h-4 w-4 shrink-0" />
                    Profile saved
                  </p>
                ) : !error ? (
                  <p className="text-sm text-muted">
                    Saves all sections — Photo, About, Rates, Skills, and Areas.
                  </p>
                ) : null}
              </div>
              <Button
                type="submit"
                className="w-full rounded-none sm:w-auto sm:min-w-[140px]"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Saving…
                  </>
                ) : (
                  'Save changes'
                )}
              </Button>
            </div>
          </div>
        </form>

        <AccountDeletionCard />
      </WorkerPortalShell>
    </DashboardLayout>
  );
}
