'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Briefcase,
  CalendarClock,
  CheckCircle2,
  CircleSlash,
  Handshake,
  Loader2,
  MessageCircle,
  UserRound,
} from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Button } from '@/components/ui/button';
import { WorkerPortalShell } from '@/components/worker/WorkerPortal';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { cn } from '@/lib/utils';

export default function WorkerAvailabilityPage() {
  const { user, refreshUser } = useAuth();
  const profile = user?.workerProfile as
    | { isAvailable?: boolean; isHired?: boolean; isVerified?: boolean }
    | undefined;

  const [isAvailable, setIsAvailable] = useState(true);
  const [isHired, setIsHired] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

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

  useEffect(() => {
    if (!profile) return;
    setIsAvailable(profile.isAvailable ?? true);
    setIsHired(profile.isHired === true);
  }, [profile]);

  const handleSetAvailable = async (next: boolean) => {
    if (saving || next === isAvailable) return;
    if (next && isHired) {
      setError(
        'You are currently hired. Mark that hire as complete before setting yourself available again.'
      );
      return;
    }

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

    try {
      await api('/users/worker/profile', {
        method: 'PATCH',
        body: JSON.stringify({ isAvailable: next }),
      });
      setIsAvailable(next);
      setSuccess(true);
      await refreshUser();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update availability');
    } finally {
      setSaving(false);
    }
  };

  const status = isHired ? 'hired' : isAvailable ? 'available' : 'unavailable';

  const statusCopy = {
    available: {
      eyebrow: 'Open for work',
      title: 'You’re available',
      body: JOBS_FEATURE_ENABLED
        ? 'Customers can see you as available in search and can invite or message you for new work.'
        : 'Customers browsing the directory can see you as available and send hire invitations or messages.',
      tone: 'available' as const,
    },
    unavailable: {
      eyebrow: 'Paused',
      title: 'You’re unavailable',
      body: 'Your profile can still be viewed, but customers will see that you’re not taking new work right now.',
      tone: 'unavailable' as const,
    },
    hired: {
      eyebrow: 'On a hire',
      title: 'You’re currently hired',
      body: 'Availability is locked while a hire is active. Once the customer marks it complete, you can open up for new work again.',
      tone: 'hired' as const,
    },
  }[status];

  return (
    <DashboardLayout role="worker" title="Availability">
      <WorkerPortalShell>
        {/* Status hero */}
        <section
          className={cn(
            'border px-4 py-5 sm:px-6 sm:py-6',
            status === 'available' && 'border-emerald-200 bg-emerald-50/80',
            status === 'unavailable' && 'border-[#e2ddd2] bg-[var(--home-sand)]/60',
            status === 'hired' && 'border-rose-200 bg-rose-50/80'
          )}
        >
          <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
            <div className="min-w-0">
              <p
                className={cn(
                  'text-[10px] font-semibold uppercase tracking-[0.14em]',
                  status === 'available' && 'text-emerald-700',
                  status === 'unavailable' && 'text-[var(--home-amber)]',
                  status === 'hired' && 'text-rose-700'
                )}
              >
                {statusCopy.eyebrow}
              </p>
              <h2 className="home-display mt-1 text-2xl font-bold text-[var(--home-ink)]">
                {statusCopy.title}
              </h2>
              <p className="mt-2 max-w-xl text-sm leading-relaxed text-slate-600">
                {statusCopy.body}
              </p>
            </div>

            <div
              className={cn(
                'flex h-14 w-14 shrink-0 items-center justify-center text-white sm:h-16 sm:w-16',
                status === 'available' && 'bg-emerald-600',
                status === 'unavailable' && 'bg-[var(--home-ink)]',
                status === 'hired' && 'bg-rose-600'
              )}
            >
              {status === 'available' ? (
                <CheckCircle2 className="h-7 w-7 sm:h-8 sm:w-8" />
              ) : status === 'hired' ? (
                <Handshake className="h-7 w-7 sm:h-8 sm:w-8" />
              ) : (
                <CircleSlash className="h-7 w-7 sm:h-8 sm:w-8" />
              )}
            </div>
          </div>
        </section>

        {/* Toggle controls */}
        <section className="border border-[#e2ddd2] bg-[#fffdf9]">
          <div className="border-b border-[#e2ddd2] px-4 py-4 sm:px-5">
            <div className="flex items-center gap-2">
              <CalendarClock className="h-5 w-5 text-[var(--home-amber)]" />
              <div>
                <h3 className="font-bold text-[var(--home-ink)]">Set your status</h3>
                <p className="text-sm text-muted">
                  Switch anytime. Changes show on your public profile right away.
                </p>
              </div>
            </div>
          </div>

          <div className="grid gap-0 sm:grid-cols-2">
            <button
              type="button"
              disabled={saving || isHired}
              onClick={() => handleSetAvailable(true)}
              className={cn(
                'flex items-start gap-3 border-b border-[#e2ddd2] px-4 py-4 text-left transition-colors sm:border-b-0 sm:border-r',
                isAvailable && !isHired
                  ? 'bg-emerald-50/90'
                  : 'bg-transparent hover:bg-white disabled:opacity-60',
                isHired && 'cursor-not-allowed'
              )}
            >
              <span
                className={cn(
                  'mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center border-2',
                  isAvailable && !isHired
                    ? 'border-emerald-600 bg-emerald-600 text-white'
                    : 'border-slate-300 bg-white'
                )}
              >
                {isAvailable && !isHired ? <CheckCircle2 className="h-3.5 w-3.5" /> : null}
              </span>
              <span>
                <span className="block text-sm font-bold text-[var(--home-ink)]">Available</span>
                <span className="mt-0.5 block text-xs leading-relaxed text-muted">
                  Open to hire invitations and new messages from customers.
                </span>
              </span>
            </button>

            <button
              type="button"
              disabled={saving || isHired}
              onClick={() => handleSetAvailable(false)}
              className={cn(
                'flex items-start gap-3 px-4 py-4 text-left transition-colors',
                !isAvailable && !isHired
                  ? 'bg-[var(--home-sand)]/80'
                  : 'bg-transparent hover:bg-white disabled:opacity-60',
                isHired && 'cursor-not-allowed'
              )}
            >
              <span
                className={cn(
                  'mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center border-2',
                  !isAvailable && !isHired
                    ? 'border-[var(--home-ink)] bg-[var(--home-ink)] text-white'
                    : 'border-slate-300 bg-white'
                )}
              >
                {!isAvailable && !isHired ? <CircleSlash className="h-3.5 w-3.5" /> : null}
              </span>
              <span>
                <span className="block text-sm font-bold text-[var(--home-ink)]">Unavailable</span>
                <span className="mt-0.5 block text-xs leading-relaxed text-muted">
                  Pause new hires when you’re booked, resting, or away.
                </span>
              </span>
            </button>
          </div>

          <div className="border-t border-[#e2ddd2] px-4 py-3 sm:px-5">
            {saving ? (
              <p className="flex items-center gap-2 text-sm text-muted">
                <Loader2 className="h-4 w-4 animate-spin" />
                Saving…
              </p>
            ) : null}
            {error ? <p className="text-sm text-red-600">{error}</p> : null}
            {success && !error ? (
              <p className="text-sm font-medium text-emerald-700">Availability updated.</p>
            ) : null}
            {isHired ? (
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <p className="text-sm text-rose-800">
                  Finish your active hire before changing availability.
                </p>
                <Link href="/worker/hire-invitations">
                  <Button size="sm" variant="outline" className="rounded-none">
                    View hire invitations
                  </Button>
                </Link>
              </div>
            ) : null}
            {!saving && !error && !success && !isHired ? (
              <p className="text-xs text-muted">
                Tip: turn unavailable when you’re fully booked so customers don’t wait on a reply.
              </p>
            ) : null}
          </div>
        </section>

        {/* What customers see */}
        <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)]">What customers see</h3>
            <p className="mt-1 text-sm text-muted">
              Your public profile badge updates based on this setting.
            </p>
          </div>
          <ul className="divide-y divide-[#ebe6db]">
            <li className="flex items-start gap-3 px-4 py-3.5 sm:px-5">
              <span className="mt-0.5 bg-[var(--home-amber)] px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white">
                Available
              </span>
              <p className="text-sm text-slate-600">
                Amber “Available” badge — customers can message and send hire invitations.
              </p>
            </li>
            <li className="flex items-start gap-3 px-4 py-3.5 sm:px-5">
              <span className="mt-0.5 bg-slate-500 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white">
                Busy
              </span>
              <p className="text-sm text-slate-600">
                Shown when you mark unavailable — profile stays visible, but you’re not open for
                new hires.
              </p>
            </li>
            <li className="flex items-start gap-3 px-4 py-3.5 sm:px-5">
              <span className="mt-0.5 bg-rose-600 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white">
                Hired
              </span>
              <p className="text-sm text-slate-600">
                Automatic while an accepted hire is in progress. Clears when the hire is completed.
              </p>
            </li>
          </ul>
        </section>

        {/* Related actions */}
        <section className="grid gap-3 sm:grid-cols-3">
          <Link
            href="/worker/profile"
            className="flex items-start gap-3 border border-[#e2ddd2] bg-[#fffdf9] p-4 transition-colors hover:border-[var(--home-amber)]/50 hover:bg-white"
          >
            <UserRound className="mt-0.5 h-5 w-5 shrink-0 text-[var(--home-amber)]" />
            <span>
              <span className="block text-sm font-bold text-[var(--home-ink)]">Edit profile</span>
              <span className="mt-0.5 block text-xs text-muted">Rates, skills, and areas</span>
            </span>
          </Link>
          <Link
            href="/worker/hire-invitations"
            className="flex items-start gap-3 border border-[#e2ddd2] bg-[#fffdf9] p-4 transition-colors hover:border-[var(--home-amber)]/50 hover:bg-white"
          >
            <Briefcase className="mt-0.5 h-5 w-5 shrink-0 text-[var(--home-amber)]" />
            <span>
              <span className="block text-sm font-bold text-[var(--home-ink)]">Hire invitations</span>
              <span className="mt-0.5 block text-xs text-muted">Accept or complete offers</span>
            </span>
          </Link>
          <Link
            href="/worker/messages"
            className="flex items-start gap-3 border border-[#e2ddd2] bg-[#fffdf9] p-4 transition-colors hover:border-[var(--home-amber)]/50 hover:bg-white"
          >
            <MessageCircle className="mt-0.5 h-5 w-5 shrink-0 text-[var(--home-amber)]" />
            <span>
              <span className="block text-sm font-bold text-[var(--home-ink)]">Messages</span>
              <span className="mt-0.5 block text-xs text-muted">Reply to customers</span>
            </span>
          </Link>
        </section>
      </WorkerPortalShell>
    </DashboardLayout>
  );
}
