'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  Briefcase,
  Clock3,
  Images,
  MapPin,
  Star,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { api, getUploadUrl } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { useRegion } from '@/contexts/RegionContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { formatWorkerRate, getRateTypeLabel } from '@/lib/rateType';
import { WorkerLocationMap } from '@/components/map/WorkerLocationMap';
import { WorkerReviewsSection } from '@/components/reviews/WorkerReviewsSection';
import { StarRating } from '@/components/reviews/StarRating';
import { WorkerProfileNav, type WorkerProfileNavItem } from '@/components/workers/WorkerProfileNav';
import {
  WorkerProfileBadges,
  WorkerSkillsBadges,
  WorkerAvatar,
  getPrimaryWorkerCategory,
} from '@/components/workers/WorkerProfileDisplay';
import { PortfolioCarousel } from '@/components/workers/PortfolioCarousel';
import { ShareButton } from '@/components/share/ShareButton';
import { SaveWorkerButton } from '@/components/workers/SaveWorkerButton';
import { HireWorkerActions } from '@/components/workers/HireWorkerActions';
import { buildWorkerSharePayload } from '@/lib/share';
import { SERVICE_AREA_LABELS } from '@/lib/region';
import { formatLastActive } from '@/lib/lastActive';
import { cn } from '@/lib/utils';

export default function WorkerProfilePage() {
  const { id } = useParams<{ id: string }>();
  const { user: authUser } = useAuth();
  const { regionPath } = useRegion();
  const { t } = useLanguage();
  const [worker, setWorker] = useState<Record<string, unknown> | null>(null);

  useEffect(() => {
    if (!id) return;
    api<{ data: Record<string, unknown> }>(`/workers/${id}`)
      .then((res) => setWorker(res.data))
      .catch(console.error);
  }, [id]);

  useEffect(() => {
    if (!worker) return;
    const hash = window.location.hash.slice(1);
    if (!hash) return;
    requestAnimationFrame(() => {
      document.getElementById(hash)?.scrollIntoView({ behavior: 'smooth' });
    });
  }, [worker]);

  if (!worker) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center bg-[#f7f4ee] text-muted">
        <div className="loading-spinner" />
      </div>
    );
  }

  const workerUser = worker.user as Record<string, string>;
  const workerProfileId = worker.id as string;
  const isOwnProfile = authUser?.workerProfile?.id === workerProfileId;
  const canInteract = !isOwnProfile && authUser?.role !== 'WORKER';
  const isLoggedInCustomer = authUser?.role === 'CUSTOMER';
  const skills = worker.skills as { category: { id: string; name: string; slug?: string } }[];
  const otherSkillsText =
    typeof worker.otherSkills === 'string' && worker.otherSkills.trim()
      ? worker.otherSkills.trim()
      : '';
  const isStudent = worker.isStudent === true;
  const areas = worker.serviceAreas as { area: string }[];
  const portfolio = worker.portfolioImages as {
    id: string;
    url: string;
    title?: string;
    description?: string;
  }[];
  const averageRating = Number(worker.averageRating) || 0;
  const totalReviews = Number(worker.totalReviews) || 0;
  const totalJobs = Number(worker.totalJobs) || 0;
  const experienceYears = Number(worker.experienceYears) || 0;
  const hasBio = typeof worker.bio === 'string' && worker.bio.length > 0;
  const hasPortfolio = portfolio?.length > 0;
  const primaryCategory = getPrimaryWorkerCategory(skills);
  const isAvailable = worker.isAvailable === true;
  const isHired = worker.isHired === true;
  const workersBackHref = regionPath('/workers');
  const rateLabel = worker.hourlyRate
    ? formatWorkerRate(Number(worker.hourlyRate), worker.rateType as string)
    : null;
  const fullName = `${workerUser.firstName} ${workerUser.lastName}`;
  const lastActiveLabel = formatLastActive(workerUser.lastActiveAt);

  const availabilityLabel = isHired
    ? t('Hired / Working', 'Hired / May trabaho')
    : isAvailable
      ? t('Available', 'Available')
      : t('Busy', 'Busy');

  const navItems: WorkerProfileNavItem[] = [
    ...(hasBio ? [{ id: 'about', label: 'About', shortLabel: 'About' }] : []),
    { id: 'skills', label: 'Skills', shortLabel: 'Skills' },
    { id: 'areas', label: 'Service Areas', shortLabel: 'Areas' },
    { id: 'portfolio', label: 'Portfolio', shortLabel: 'Photos' },
    { id: 'reviews', label: 'Reviews', shortLabel: 'Reviews' },
  ];

  const sectionClass = 'worker-profile-section scroll-mt-[7.5rem] sm:scroll-mt-28';
  const sharePayload = buildWorkerSharePayload(worker);

  const metrics = [
    {
      label: 'Rating',
      value: averageRating > 0 ? averageRating.toFixed(1) : '—',
      hint: totalReviews > 0 ? `${totalReviews} reviews` : 'No reviews yet',
      href: '#reviews',
    },
    {
      label: 'Experience',
      value: experienceYears > 0 ? `${experienceYears}` : '—',
      hint: experienceYears === 1 ? 'year' : 'years',
    },
    {
      label: 'Completed',
      value: String(totalJobs),
      hint: totalJobs === 1 ? 'job' : 'jobs',
    },
    {
      label: 'Rate',
      value: rateLabel ?? '—',
      hint: worker.hourlyRate ? getRateTypeLabel(worker.rateType as string) : 'Ask to confirm',
      accent: Boolean(rateLabel),
    },
  ];

  return (
    <div className="worker-profile-page pb-10 sm:pb-12">
      <section className="worker-profile-hero">
        <div className="mx-auto max-w-6xl px-4 pb-8 pt-4 sm:px-6 sm:pb-10 sm:pt-5">
          <div className="mb-6 flex items-center justify-between gap-3">
            <Link
              href={workersBackHref}
              className="inline-flex items-center gap-1.5 text-sm text-slate-300 transition-colors hover:text-white"
            >
              <ArrowLeft className="h-4 w-4 shrink-0" />
              <span className="hidden sm:inline">Back to directory</span>
              <span className="sm:hidden">Back</span>
            </Link>
            <div className="flex shrink-0 items-center gap-2">
              {isLoggedInCustomer ? (
                <SaveWorkerButton
                  workerId={workerProfileId}
                  buttonVariant="heroOutline"
                  size="sm"
                  className="shrink-0 rounded-none border-white/25 max-sm:px-2.5"
                />
              ) : null}
              <ShareButton
                payload={sharePayload}
                variant="heroOutline"
                size="sm"
                label="Share"
                className="shrink-0 rounded-none border-white/25 max-sm:px-2.5"
              />
            </div>
          </div>

          <div className="flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between lg:gap-10">
            <div className="flex min-w-0 flex-1 gap-4 sm:gap-5">
              <WorkerAvatar
                user={{
                  firstName: workerUser.firstName,
                  lastName: workerUser.lastName,
                  avatarUrl: workerUser.avatarUrl,
                }}
                size="xl"
                rounded="none"
                className="h-20 w-20 ring-2 ring-white/25 sm:h-28 sm:w-28 sm:ring-[3px]"
              />

              <div className="min-w-0 flex-1 self-center">
                {primaryCategory ? (
                  <p className="text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-400/90 sm:text-[11px]">
                    {primaryCategory.name}
                  </p>
                ) : null}

                <div className="mt-1 flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
                  <h1 className="home-display text-2xl font-bold leading-tight tracking-tight sm:text-3xl md:text-[2.15rem]">
                    {fullName}
                  </h1>
                  <WorkerProfileBadges
                    isVerified={worker.isVerified === true}
                    isStudent={isStudent}
                    tone="onDark"
                  />
                </div>

                {worker.headline ? (
                  <p className="mt-2 max-w-2xl text-sm leading-relaxed text-slate-300 sm:text-[0.9375rem]">
                    {worker.headline as string}
                  </p>
                ) : null}

                <div className="mt-3.5 flex flex-wrap items-center gap-2">
                  <span
                    className={cn(
                      'inline-flex items-center px-2.5 py-1 text-[11px] font-bold uppercase tracking-wide',
                      isHired
                        ? 'bg-rose-600 text-white'
                        : isAvailable
                          ? 'bg-[var(--home-amber)] text-white'
                          : 'bg-white/15 text-slate-200'
                    )}
                  >
                    {availabilityLabel}
                  </span>
                  {lastActiveLabel ? (
                    <span className="inline-flex items-center gap-1.5 bg-emerald-500/15 px-2.5 py-1 text-[11px] font-semibold text-emerald-200">
                      <Clock3 className="h-3 w-3" />
                      {lastActiveLabel}
                    </span>
                  ) : null}
                  <Link
                    href="#reviews"
                    className="inline-flex items-center gap-1.5 bg-white/10 px-2.5 py-1 text-xs text-slate-200 transition-colors hover:bg-white/15"
                  >
                    <Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" />
                    <span className="font-semibold tabular-nums text-white">
                      {averageRating > 0 ? averageRating.toFixed(1) : '—'}
                    </span>
                    <span className="text-slate-400">({totalReviews})</span>
                  </Link>
                </div>
              </div>
            </div>

            {canInteract ? (
              <div className="w-full shrink-0 lg:hidden">
                <HireWorkerActions
                  workerProfileId={workerProfileId}
                  workerName={fullName}
                  isHired={isHired}
                  isAvailable={isAvailable}
                  tone="onDark"
                />
              </div>
            ) : null}
          </div>
        </div>
      </section>

      {/* Metrics band */}
      <div className="border-b border-[#e2ddd2] bg-white">
        <div className="mx-auto grid max-w-6xl grid-cols-2 lg:grid-cols-4">
          {metrics.map((metric, index) => {
            const inner = (
              <>
                <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted">
                  {metric.label}
                </p>
                <p
                  className={cn(
                    'home-display mt-1 text-xl font-bold tabular-nums tracking-tight sm:text-2xl',
                    metric.accent ? 'text-[var(--home-amber)]' : 'text-[var(--home-ink)]'
                  )}
                >
                  {metric.value}
                </p>
                <p className="mt-0.5 text-xs text-muted">{metric.hint}</p>
              </>
            );
            return metric.href ? (
              <Link
                key={metric.label}
                href={metric.href}
                className={cn(
                  'border-[#e2ddd2] px-4 py-4 transition-colors hover:bg-[var(--home-sand)]/40 sm:px-5 sm:py-5',
                  index % 2 === 1 && 'border-l',
                  index >= 2 && 'border-t lg:border-t-0',
                  index >= 1 && 'lg:border-l'
                )}
              >
                {inner}
              </Link>
            ) : (
              <div
                key={metric.label}
                className={cn(
                  'border-[#e2ddd2] px-4 py-4 sm:px-5 sm:py-5',
                  index % 2 === 1 && 'border-l',
                  index >= 2 && 'border-t lg:border-t-0',
                  index >= 1 && 'lg:border-l'
                )}
              >
                {inner}
              </div>
            );
          })}
        </div>
      </div>

      <div className="mx-auto max-w-6xl px-4 sm:px-6">
        <WorkerProfileNav items={navItems} />

        <div className="grid gap-5 py-5 lg:grid-cols-[minmax(0,1fr)_300px] lg:items-start lg:gap-7 lg:py-7">
          <div className="space-y-4 sm:space-y-5">
            {hasBio ? (
              <section id="about" className={sectionClass}>
                <h2 className="worker-profile-section-title">About</h2>
                <p className="text-[0.9375rem] leading-relaxed text-slate-700 whitespace-pre-wrap">
                  {worker.bio as string}
                </p>
              </section>
            ) : null}

            <section id="skills" className={sectionClass}>
              <h2 className="worker-profile-section-title">Skills & trades</h2>
              <WorkerSkillsBadges
                skills={skills}
                otherSkills={otherSkillsText}
                badgeClassName="rounded-none border border-[#e2ddd2] bg-white px-2.5 py-1 text-xs font-medium text-slate-800"
              />
            </section>

            <section id="areas" className={sectionClass}>
              <h2 className="worker-profile-section-title">Service areas</h2>
              <div className="mb-4 flex flex-wrap gap-1.5">
                {areas?.map((a) => (
                  <Badge
                    key={a.area}
                    variant="secondary"
                    className="gap-1 rounded-none border border-[#e2ddd2] bg-white font-medium text-slate-800"
                  >
                    <MapPin className="h-3 w-3 shrink-0 text-[var(--home-amber)]" />
                    {SERVICE_AREA_LABELS[a.area as keyof typeof SERVICE_AREA_LABELS] ?? a.area}
                  </Badge>
                ))}
              </div>
              <div className="overflow-hidden border border-[#e2ddd2]">
                <WorkerLocationMap
                  worker={{ id: worker.id as string, serviceAreas: areas }}
                  areaLabels={SERVICE_AREA_LABELS}
                  showHeading={false}
                />
              </div>
            </section>

            <section id="portfolio" className={sectionClass}>
              <div className="mb-4 flex items-end justify-between gap-2">
                <h2 className="worker-profile-section-title mb-0">Portfolio</h2>
                {hasPortfolio ? (
                  <span className="text-xs font-medium tabular-nums text-muted">
                    {portfolio.length} photo{portfolio.length !== 1 ? 's' : ''}
                  </span>
                ) : null}
              </div>
              {hasPortfolio ? (
                <PortfolioCarousel images={portfolio} getImageUrl={getUploadUrl} />
              ) : (
                <div className="flex flex-col items-center border border-dashed border-[#d6d0c4] bg-[var(--home-sand)]/40 px-4 py-12 text-center">
                  <Images className="mb-2 h-8 w-8 text-slate-300" />
                  <p className="text-sm font-semibold text-slate-800">No portfolio photos yet</p>
                  <p className="mt-1 max-w-xs text-xs text-muted">
                    Work samples help customers understand quality and style.
                  </p>
                </div>
              )}
            </section>

            <WorkerReviewsSection
              workerId={worker.id as string}
              averageRating={averageRating}
              totalReviews={totalReviews}
            />
          </div>

          {/* Professional sidebar */}
          <aside className="hidden lg:block">
            <div className="sticky top-6 space-y-4">
              <div className="border border-[#e2ddd2] bg-white p-5 shadow-[0_10px_30px_rgba(12,25,41,0.06)]">
                <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted">
                  Engagement
                </p>
                <p
                  className={cn(
                    'home-display mt-2 text-2xl font-bold tracking-tight',
                    rateLabel ? 'text-[var(--home-amber)]' : 'text-[var(--home-ink)]'
                  )}
                >
                  {rateLabel ?? 'Rate on request'}
                </p>
                <p className="mt-1 text-sm text-muted">
                  {worker.hourlyRate
                    ? getRateTypeLabel(worker.rateType as string)
                    : 'Confirm pricing when you message'}
                </p>

                <div className="mt-4 space-y-2 border-t border-[#ebe6db] pt-4 text-sm">
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-muted">Status</span>
                    <span
                      className={cn(
                        'font-semibold',
                        isHired
                          ? 'text-rose-700'
                          : isAvailable
                            ? 'text-emerald-700'
                            : 'text-slate-600'
                      )}
                    >
                      {availabilityLabel}
                    </span>
                  </div>
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-muted">Jobs done</span>
                    <span className="font-semibold tabular-nums text-[var(--home-ink)]">
                      {totalJobs}
                    </span>
                  </div>
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-muted">Reviews</span>
                    <span className="inline-flex items-center gap-1 font-semibold text-[var(--home-ink)]">
                      <StarRating rating={averageRating} showValue size="sm" />
                    </span>
                  </div>
                </div>

                {canInteract ? (
                  <HireWorkerActions
                    workerProfileId={workerProfileId}
                    workerName={fullName}
                    isHired={isHired}
                    isAvailable={isAvailable}
                    tone="onLight"
                    className="mt-5"
                  />
                ) : isOwnProfile ? (
                  <p className="mt-5 border border-[#e2ddd2] bg-[var(--home-sand)]/50 px-3 py-2.5 text-sm text-slate-600">
                    This is how customers see your public profile.
                  </p>
                ) : null}
              </div>

              <div className="border border-[#e2ddd2] bg-[#fffdf9] p-4">
                <p className="flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted">
                  <Briefcase className="h-3.5 w-3.5 text-[var(--home-amber)]" />
                  Profile tips
                </p>
                <ul className="mt-3 space-y-2 text-xs leading-relaxed text-slate-600">
                  <li>Verified workers appear higher in search and map results.</li>
                  <li>Clear rates and service areas help customers reach out faster.</li>
                  <li>Recent activity signals responsiveness.</li>
                </ul>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}
