'use client';

import { useEffect, useId, useState } from 'react';
import { createPortal } from 'react-dom';
import Link from 'next/link';
import { AlertTriangle, ShieldAlert, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

const awarenessPoints = [
  'Workers on eHandyHire are independent contractors — not employees, agents, or partners of our company.',
  'Any work agreement, schedule, payment, and quality expectations are strictly between you and the worker.',
  'eHandyHire does not guarantee results, safety, licensing, insurance, or background beyond what is shown on the profile.',
  'You are responsible for evaluating the worker, asking questions, and deciding whether to proceed.',
  'eHandyHire is not liable for injuries, property damage, theft, delays, poor workmanship, or payment disputes.',
];

interface HireDisclaimerModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: () => void;
  workerName?: string;
  /** accept-quote = confirming a worker application; hire-worker = legacy job post; send-hire-invite = direct profile hire */
  intent?: 'accept-quote' | 'hire-worker' | 'send-hire-invite';
  confirmLabel?: string;
  loading?: boolean;
}

export function HireDisclaimerModal({
  open,
  onClose,
  onConfirm,
  workerName,
  intent = 'hire-worker',
  confirmLabel,
  loading = false,
}: HireDisclaimerModalProps) {
  const [acknowledged, setAcknowledged] = useState(false);
  const [showAckHint, setShowAckHint] = useState(false);
  const [mounted, setMounted] = useState(false);
  const titleId = useId();
  const checkboxId = useId();

  const resolvedConfirmLabel =
    confirmLabel ??
    (intent === 'accept-quote'
      ? 'Accept & hire worker'
      : intent === 'send-hire-invite'
        ? 'Send hire invitation'
        : 'I understand — continue');

  const subtitle =
    intent === 'accept-quote' && workerName
      ? `Please confirm you understand the terms for hiring ${workerName}.`
      : intent === 'send-hire-invite' && workerName
        ? `You're about to send a hire invitation to ${workerName}. Please confirm you understand how hiring works.`
      : workerName
        ? `You're about to hire ${workerName}. Please confirm you understand how hiring works.`
        : 'Please confirm you understand how hiring works on eHandyHire.';

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (open) {
      setAcknowledged(false);
      setShowAckHint(false);
    }
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKeyDown);
    document.body.style.overflow = 'hidden';
    document.body.classList.add('modal-open');
    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.style.overflow = '';
      document.body.classList.remove('modal-open');
    };
  }, [open, onClose]);

  const handleConfirmClick = () => {
    if (!acknowledged) {
      setShowAckHint(true);
      return;
    }
    onConfirm();
  };

  if (!open || !mounted) return null;

  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-end sm:items-center justify-center p-0 sm:p-4">
      <button
        type="button"
        className="absolute inset-0 bg-slate-900/60 backdrop-blur-[2px]"
        aria-label="Close dialog"
        onClick={onClose}
      />

      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className={cn(
          'relative z-[10000] flex flex-col w-full sm:max-w-lg',
          'max-h-[min(92dvh,100dvh)] sm:max-h-[90vh]',
          'rounded-none sm:rounded-none border border-[#e2ddd2] bg-[#fffdf9] shadow-2xl'
        )}
      >
        <div className="shrink-0 flex items-start justify-between gap-3 border-b border-white/10 bg-[var(--home-ink)] px-5 py-4 text-white">
          <div className="flex items-start gap-3 min-w-0">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center bg-[var(--home-amber)] text-white">
              <ShieldAlert className="h-5 w-5" />
            </div>
            <div className="min-w-0">
              <h2 id={titleId} className="home-display font-bold text-lg leading-tight">
                Before you hire
              </h2>
              <p className="text-sm text-slate-300 mt-1">{subtitle}</p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="flex h-9 w-9 shrink-0 items-center justify-center text-slate-400 hover:bg-white/10 hover:text-white transition-colors"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-5 py-5 space-y-5 min-h-0">
          <div className="border border-[#e2ddd2] bg-white px-4 py-3 flex gap-3">
            <span className="flex h-9 w-9 shrink-0 items-center justify-center bg-[var(--home-ink)] text-white">
              <AlertTriangle className="h-4 w-4" />
            </span>
            <p className="text-sm text-slate-700 leading-relaxed pt-1">
              eHandyHire is a marketplace only. We connect you with independent workers but do not
              perform the work ourselves and cannot be held accountable for what happens on the job.
            </p>
          </div>

          {(intent === 'hire-worker' || intent === 'send-hire-invite') && (
            <div className="border border-[#e2ddd2] bg-white px-4 py-3 text-sm text-slate-600 leading-relaxed">
              <p className="font-semibold text-slate-900 mb-1">What happens next</p>
              {intent === 'send-hire-invite' ? (
                <p>
                  We&apos;ll send a hire invitation to{' '}
                  {workerName ? workerName : 'this worker'}. They can accept or reject.
                  If accepted, their profile will show as hired so other customers know
                  they are currently working.
                </p>
              ) : (
                <p>
                  You&apos;ll describe the work you need on the next screen.
                  {workerName ? ` ${workerName} and other matching workers` : ' Matching workers'}{' '}
                  can then apply — you choose who to hire.
                </p>
              )}
            </div>
          )}

          <ul className="space-y-3 pb-2">
            {awarenessPoints.map((point) => (
              <li key={point} className="flex gap-3 text-sm text-slate-600 leading-relaxed">
                <span className="mt-2 h-1.5 w-1.5 shrink-0 bg-[var(--home-amber)]" />
                <span>{point}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="shrink-0 border-t border-[#e2ddd2] bg-[#fffdf9] px-5 py-4 space-y-4 pb-[max(1rem,env(safe-area-inset-bottom))]">
          <label
            htmlFor={checkboxId}
            className={cn(
              'flex items-start gap-3 border px-4 py-3 cursor-pointer transition-colors',
              acknowledged
                ? 'border-[var(--home-amber)]/40 bg-[var(--home-sand)]'
                : 'border-[#e2ddd2] bg-white hover:bg-[var(--home-sand)]/60',
              showAckHint && !acknowledged && 'border-[var(--home-amber)] ring-2 ring-[var(--home-amber)]/25'
            )}
          >
            <input
              id={checkboxId}
              type="checkbox"
              checked={acknowledged}
              onChange={(e) => {
                setAcknowledged(e.target.checked);
                if (e.target.checked) setShowAckHint(false);
              }}
              className="mt-0.5 h-4 w-4 shrink-0 border-[#d6d0c4] text-[var(--home-amber)] focus:ring-[var(--home-amber)]/30"
            />
            <span className="text-sm text-slate-700 leading-relaxed">
              I understand this worker is independent, that I hire at my own risk, and that eHandyHire
              is not responsible for services performed. I have read the{' '}
              <Link
                href="/disclaimer"
                target="_blank"
                className="text-[var(--home-amber)] font-semibold hover:text-[var(--home-amber-soft)]"
                onClick={(e) => e.stopPropagation()}
              >
                full disclaimer
              </Link>
              .
            </span>
          </label>

          {showAckHint && !acknowledged && (
            <p className="text-sm text-[var(--home-amber)] font-medium -mt-2">
              Please check the box above to continue.
            </p>
          )}

          <div className="flex flex-col-reverse sm:flex-row gap-2">
            <Button
              type="button"
              variant="outline"
              className="w-full sm:flex-1 rounded-none border-[#d6d0c4]"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button
              type="button"
              className="w-full sm:flex-1 worker-cta-amber rounded-none"
              disabled={loading}
              aria-disabled={!acknowledged || loading}
              onClick={handleConfirmClick}
            >
              {loading ? 'Processing...' : resolvedConfirmLabel}
            </Button>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}
