'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import {
  AlertTriangle,
  Bell,
  Briefcase,
  CalendarClock,
  ClipboardList,
  ExternalLink,
  FolderOpen,
  Handshake,
  MessageCircle,
  ShieldCheck,
  Star,
  UserRound,
} from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Button } from '@/components/ui/button';
import { WorkerPortalShell } from '@/components/worker/WorkerPortal';
import { WorkerAvatar, WorkerProfileBadges } from '@/components/workers/WorkerProfileDisplay';
import { api, getUploadUrl } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { cn } from '@/lib/utils';

type DashboardStats = Record<string, number>;

type WorkerDashMeta = {
  id?: string;
  isVerified?: boolean;
  isAvailable?: boolean;
  isHired?: boolean;
  totalJobs?: number;
  averageRating?: number;
  totalReviews?: number;
};

function MetricTile({
  href,
  label,
  value,
  hint,
  emphasize,
}: {
  href: string;
  label: string;
  value: string | number;
  hint?: string;
  emphasize?: boolean;
}) {
  return (
    <Link
      href={href}
      className={cn(
        'border border-[#e2ddd2] bg-[#fffdf9] p-4 transition-colors hover:border-[var(--home-amber)]/45 hover:bg-white',
        emphasize && 'border-amber-300 bg-amber-50/70'
      )}
    >
      <p
        className={cn(
          'text-2xl font-bold tabular-nums tracking-tight',
          emphasize ? 'text-amber-800' : 'text-[var(--home-ink)]'
        )}
      >
        {value}
      </p>
      <p className="mt-1 text-xs font-semibold uppercase tracking-[0.08em] text-slate-600">
        {label}
      </p>
      {hint ? <p className="mt-1 text-[11px] text-muted">{hint}</p> : null}
    </Link>
  );
}

function ActionLink({
  href,
  icon: Icon,
  label,
  description,
  badge,
  bordered = true,
}: {
  href: string;
  icon: typeof MessageCircle;
  label: string;
  description: string;
  badge?: string | number | null;
  bordered?: boolean;
}) {
  return (
    <Link
      href={href}
      className={cn(
        'flex items-start gap-3 p-4 transition-colors hover:bg-[var(--home-sand)]/40',
        bordered &&
          'border border-[#e2ddd2] bg-[#fffdf9] hover:border-[var(--home-amber)]/50 hover:bg-white'
      )}
    >
      <span className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center bg-[var(--home-ink)] text-white">
        <Icon className="h-4 w-4" />
      </span>
      <span className="min-w-0 flex-1">
        <span className="flex items-center gap-2">
          <span className="text-sm font-bold text-[var(--home-ink)]">{label}</span>
          {badge != null && Number(badge) > 0 ? (
            <span className="bg-[var(--home-amber)] px-1.5 py-0.5 text-[10px] font-bold text-white">
              {badge}
            </span>
          ) : null}
        </span>
        <span className="mt-0.5 block text-xs leading-relaxed text-muted">{description}</span>
      </span>
    </Link>
  );
}

export default function WorkerDashboard() {
  const { user, refreshUser } = useAuth();
  const [stats, setStats] = useState<DashboardStats>({});
  const [workerMeta, setWorkerMeta] = useState<WorkerDashMeta | null>(null);
  const [loadingStats, setLoadingStats] = useState(true);

  const loadStats = useCallback(async () => {
    try {
      const res = await api<{
        data: { stats: DashboardStats; worker?: WorkerDashMeta };
      }>('/users/worker/dashboard');
      setStats(res.data.stats || {});
      setWorkerMeta(res.data.worker || null);
    } catch (e) {
      console.error(e);
    } finally {
      setLoadingStats(false);
    }
  }, []);

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

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

  useEffect(() => {
    const onFocus = () => {
      void loadStats();
      void refreshUser();
    };
    const onVisibility = () => {
      if (document.visibilityState === 'visible') onFocus();
    };
    window.addEventListener('focus', onFocus);
    document.addEventListener('visibilitychange', onVisibility);
    return () => {
      window.removeEventListener('focus', onFocus);
      document.removeEventListener('visibilitychange', onVisibility);
    };
  }, [loadStats, refreshUser]);

  const profile = user?.workerProfile as
    | {
        id?: string;
        isVerified?: boolean;
        isAvailable?: boolean;
        isHired?: boolean;
        headline?: string | null;
        displayName?: string | null;
        totalJobs?: number;
      }
    | undefined;

  const isVerified = workerMeta?.isVerified ?? profile?.isVerified ?? false;
  const isHired = workerMeta?.isHired ?? profile?.isHired === true;
  const isAvailable = workerMeta?.isAvailable ?? profile?.isAvailable ?? true;
  const workerId = workerMeta?.id ?? profile?.id;
  const publicProfileHref = workerId ? `/workers/${workerId}` : null;

  const availabilityLabel = isHired ? 'Hired' : isAvailable ? 'Available' : 'Unavailable';
  const shownName =
    profile?.displayName?.trim() ||
    `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim() ||
    'Worker';

  const deletionScheduled =
    typeof user?.deletionScheduledFor === 'string' ? user.deletionScheduledFor : null;

  const unreadMessages = loadingStats ? '—' : stats.unreadMessages || 0;
  const unreadNotifications = loadingStats ? '—' : stats.unreadNotifications || 0;
  const pendingHires = loadingStats ? '—' : stats.pendingHireInvitations || 0;
  const rating = loadingStats ? '—' : Number(stats.averageRating || 0).toFixed(1);
  const reviews = loadingStats ? '—' : stats.totalReviews || 0;
  const jobsDone = loadingStats ? '—' : stats.totalJobs || profile?.totalJobs || 0;

  const needsAttention =
    !isVerified ||
    Number(stats.unreadMessages || 0) > 0 ||
    Number(stats.pendingHireInvitations || 0) > 0 ||
    Boolean(deletionScheduled);

  return (
    <DashboardLayout role="worker" title="Dashboard">
      <WorkerPortalShell>
        {/* Welcome / status */}
        <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: user?.avatarUrl ? getUploadUrl(user.avatarUrl) : null,
                }}
                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)]">
                  Worker portal
                </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)]">
                    Hello, {user?.firstName || 'there'}
                  </h2>
                  <WorkerProfileBadges isVerified={isVerified} />
                </div>
                <p className="mt-1 truncate text-sm text-muted">
                  {profile?.headline ||
                    (JOBS_FEATURE_ENABLED
                      ? 'Manage jobs, quotes, and your public listing'
                      : 'Manage your listing, hires, and customer messages')}
                </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>
                  <span className="border border-[#e2ddd2] bg-white px-2 py-0.5 text-[10px] font-semibold text-slate-700">
                    {shownName}
                  </span>
                </div>
              </div>
            </div>

            <div className="flex shrink-0 flex-wrap gap-2 sm:flex-col sm:items-stretch">
              <Link href="/worker/availability">
                <Button type="button" size="sm" className="w-full gap-1.5 rounded-none">
                  <CalendarClock className="h-4 w-4" />
                  Availability
                </Button>
              </Link>
              {publicProfileHref && isVerified ? (
                <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>
              ) : (
                <Link href="/worker/verification">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="w-full gap-1.5 rounded-none"
                  >
                    <ShieldCheck className="h-4 w-4" />
                    Get verified
                  </Button>
                </Link>
              )}
            </div>
          </div>
        </section>

        {/* Attention banners */}
        {deletionScheduled ? (
          <section className="border border-rose-200 bg-rose-50/80 px-4 py-4 sm:px-5">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-start gap-3">
                <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-rose-600" />
                <div>
                  <p className="font-bold text-[var(--home-ink)]">Account removal scheduled</p>
                  <p className="mt-1 text-sm text-slate-600">
                    You can cancel anytime before the scheduled date from your profile.
                  </p>
                </div>
              </div>
              <Link href="/worker/profile">
                <Button size="sm" variant="outline" className="rounded-none">
                  Manage
                </Button>
              </Link>
            </div>
          </section>
        ) : null}

        {!isVerified ? (
          <section className="border border-amber-200 bg-amber-50/80 px-4 py-4 sm:px-5">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <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-bold text-[var(--home-ink)]">
                    Your profile is hidden until verified
                  </p>
                  <p className="mt-1 text-sm text-slate-600">
                    Customers can’t find you in search or the directory yet. Upload your ID and
                    selfie so our team can verify you.
                  </p>
                </div>
              </div>
              <Link href="/worker/verification">
                <Button size="sm" className="rounded-none bg-[var(--home-amber)] hover:bg-[var(--home-amber-soft)]">
                  Verify now
                </Button>
              </Link>
            </div>
          </section>
        ) : null}

        {/* At a glance */}
        <section>
          <div className="mb-3 flex items-end justify-between gap-3">
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--home-amber)]">
                At a glance
              </p>
              <h3 className="mt-0.5 font-bold text-[var(--home-ink)]">Your numbers</h3>
            </div>
            {needsAttention && !loadingStats ? (
              <p className="text-xs font-medium text-amber-700">Items need your attention</p>
            ) : null}
          </div>

          {JOBS_FEATURE_ENABLED ? (
            <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
              <MetricTile
                href="/worker/jobs"
                label="Available jobs"
                value={loadingStats ? '—' : stats.availableJobs || 0}
              />
              <MetricTile
                href="/worker/applications"
                label="My quotes"
                value={loadingStats ? '—' : stats.myQuotations || 0}
              />
              <MetricTile
                href="/worker/accepted"
                label="Accepted"
                value={loadingStats ? '—' : stats.acceptedJobs || 0}
              />
              <MetricTile
                href="/worker/notifications"
                label="Notifications"
                value={unreadNotifications}
                emphasize={Number(stats.unreadNotifications || 0) > 0}
                hint={Number(stats.unreadNotifications || 0) > 0 ? 'Unread' : undefined}
              />
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
              <MetricTile href="/worker/ratings" label="Rating" value={rating} />
              <MetricTile href="/worker/ratings" label="Reviews" value={reviews} />
              <MetricTile
                href="/worker/messages"
                label="Messages"
                value={unreadMessages}
                emphasize={Number(stats.unreadMessages || 0) > 0}
                hint={Number(stats.unreadMessages || 0) > 0 ? 'Unread' : undefined}
              />
              <MetricTile
                href="/worker/hire-invitations"
                label="Hire invites"
                value={pendingHires}
                emphasize={Number(stats.pendingHireInvitations || 0) > 0}
                hint={
                  Number(stats.pendingHireInvitations || 0) > 0 ? 'Awaiting reply' : undefined
                }
              />
            </div>
          )}

          {!JOBS_FEATURE_ENABLED ? (
            <div className="mt-3 grid grid-cols-2 gap-3">
              <MetricTile
                href="/worker/notifications"
                label="Notifications"
                value={unreadNotifications}
                emphasize={Number(stats.unreadNotifications || 0) > 0}
              />
              <MetricTile
                href="/worker/hire-invitations"
                label="Jobs completed"
                value={jobsDone}
                hint="Completed hires"
              />
            </div>
          ) : null}
        </section>

        {/* Inbox */}
        <section className="border border-[#e2ddd2] bg-white">
          <div className="border-b border-[#e2ddd2] px-4 py-4 sm:px-5">
            <h3 className="font-bold text-[var(--home-ink)]">Inbox</h3>
            <p className="mt-1 text-sm text-muted">
              Reply to customers and stay on top of invitations.
            </p>
          </div>
          <div className="grid gap-0 sm:grid-cols-3">
            <div className="border-b border-[#e2ddd2] sm:border-b-0 sm:border-r">
              <ActionLink
                bordered={false}
                href="/worker/messages"
                icon={MessageCircle}
                label="Messages"
                description="Chat with customers who reach out"
                badge={stats.unreadMessages}
              />
            </div>
            <div className="border-b border-[#e2ddd2] sm:border-b-0 sm:border-r">
              <ActionLink
                bordered={false}
                href="/worker/hire-invitations"
                icon={Handshake}
                label="Hire invitations"
                description="Accept, reject, or complete hires"
                badge={stats.pendingHireInvitations}
              />
            </div>
            <ActionLink
              bordered={false}
              href="/worker/notifications"
              icon={Bell}
              label="Notifications"
              description="Alerts about hires, reviews, and account"
              badge={stats.unreadNotifications}
            />
          </div>
        </section>

        {/* Listing */}
        <section className="border border-[#e2ddd2] bg-white">
          <div className="border-b border-[#e2ddd2] px-4 py-4 sm:px-5">
            <h3 className="font-bold text-[var(--home-ink)]">Your listing</h3>
            <p className="mt-1 text-sm text-muted">
              Keep your public profile sharp so the right customers find you.
            </p>
          </div>
          <div className="grid gap-0 sm:grid-cols-2">
            <div className="border-b border-[#e2ddd2] sm:border-r">
              <ActionLink
                bordered={false}
                href="/worker/profile"
                icon={UserRound}
                label="Edit profile"
                description="Headline, skills, rates, and service areas"
              />
            </div>
            <div className="border-b border-[#e2ddd2]">
              <ActionLink
                bordered={false}
                href="/worker/portfolio"
                icon={FolderOpen}
                label="Portfolio"
                description="Photos of your best work"
              />
            </div>
            <div className="border-b border-[#e2ddd2] sm:border-b-0 sm:border-r">
              <ActionLink
                bordered={false}
                href="/worker/availability"
                icon={CalendarClock}
                label="Availability"
                description={
                  isHired
                    ? 'Locked while a hire is active'
                    : isAvailable
                      ? 'You’re open for new work'
                      : 'You’re marked unavailable'
                }
              />
            </div>
            <ActionLink
              bordered={false}
              href="/worker/ratings"
              icon={Star}
              label="Ratings & reviews"
              description={
                Number(stats.totalReviews || 0) > 0
                  ? `${Number(stats.averageRating || 0).toFixed(1)} average from ${stats.totalReviews} reviews`
                  : 'See what customers say about your work'
              }
            />
          </div>
        </section>

        {/* Jobs (when enabled) */}
        {JOBS_FEATURE_ENABLED ? (
          <section className="border border-[#e2ddd2] bg-white">
            <div className="border-b border-[#e2ddd2] px-4 py-4 sm:px-5">
              <h3 className="font-bold text-[var(--home-ink)]">Jobs</h3>
              <p className="mt-1 text-sm text-muted">Find work and track your quotations.</p>
            </div>
            <div className="grid gap-0 sm:grid-cols-3">
              <div className="border-b border-[#e2ddd2] sm:border-b-0 sm:border-r">
                <ActionLink
                  bordered={false}
                  href="/worker/jobs"
                  icon={Briefcase}
                  label="Browse jobs"
                  description="Open jobs that match your skills"
                />
              </div>
              <div className="border-b border-[#e2ddd2] sm:border-b-0 sm:border-r">
                <ActionLink
                  bordered={false}
                  href="/worker/applications"
                  icon={ClipboardList}
                  label="My quotes"
                  description="Quotations you’ve submitted"
                />
              </div>
              <ActionLink
                bordered={false}
                href="/worker/accepted"
                icon={Star}
                label="Accepted jobs"
                description="Work you’ve been hired for"
              />
            </div>
          </section>
        ) : null}

        {/* Verification footer CTA */}
        <section className="border border-[#e2ddd2] bg-[var(--home-sand)]/50 px-4 py-4 sm:px-5">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="font-bold text-[var(--home-ink)]">
                {isVerified ? 'You’re verified' : 'Finish verification'}
              </p>
              <p className="mt-1 text-sm text-muted">
                {isVerified
                  ? 'Customers can find and contact you in the directory.'
                  : 'Verified workers appear in search, map, and category listings.'}
              </p>
            </div>
            <Link href="/worker/verification">
              <Button size="sm" variant="outline" className="rounded-none gap-1.5">
                <ShieldCheck className="h-4 w-4" />
                {isVerified ? 'View status' : 'Upload documents'}
              </Button>
            </Link>
          </div>
        </section>
      </WorkerPortalShell>
    </DashboardLayout>
  );
}
