'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Handshake, MessageCircle, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { HireDisclaimerModal } from '@/components/legal/HireDisclaimerModal';
import { api, ApiError } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { cn } from '@/lib/utils';

interface HireWorkerActionsProps {
  workerProfileId: string;
  workerName: string;
  isHired: boolean;
  isAvailable: boolean;
  /** onDark = hero; onLight = sidebar / light surfaces */
  tone?: 'onDark' | 'onLight';
  className?: string;
}

export function HireWorkerActions({
  workerProfileId,
  workerName,
  isHired,
  isAvailable,
  tone = 'onDark',
  className,
}: HireWorkerActionsProps) {
  const router = useRouter();
  const { user } = useAuth();
  const { t } = useLanguage();
  const [modalOpen, setModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sent, setSent] = useState(false);

  const unavailable = isHired || !isAvailable;
  const customerProfile = user?.customerProfile as
    | { isVerified?: boolean }
    | undefined;
  const isCustomer = user?.role === 'CUSTOMER';
  const isCustomerVerified = customerProfile?.isVerified === true;
  const needsVerification = isCustomer && !isCustomerVerified;
  const onDark = tone === 'onDark';

  const requireCustomerOrLogin = () => {
    if (!user) {
      router.push(`/login?redirect=${encodeURIComponent(`/workers/${workerProfileId}`)}`);
      return false;
    }
    if (user.role !== 'CUSTOMER') {
      setError(
        t(
          'Only customer accounts can hire or message workers.',
          'Customer accounts lang ang puwedeng mag-hire o mag-message ng workers.'
        )
      );
      return false;
    }
    return true;
  };

  const openHireFlow = () => {
    setError(null);
    if (!requireCustomerOrLogin()) return;
    if (needsVerification) {
      router.push('/customer/verification');
      return;
    }
    setModalOpen(true);
  };

  const openMessage = () => {
    setError(null);
    if (!requireCustomerOrLogin()) return;
    if (needsVerification) {
      router.push('/customer/verification');
      return;
    }
    router.push(`/customer/messages?workerId=${workerProfileId}`);
  };

  const sendInvitation = async () => {
    setLoading(true);
    setError(null);
    try {
      await api('/hire-invitations', {
        method: 'POST',
        body: JSON.stringify({
          workerId: workerProfileId,
          acknowledgedDisclaimer: true,
        }),
      });
      setSent(true);
      setModalOpen(false);
    } catch (err) {
      const message =
        err instanceof ApiError
          ? err.message
          : t('Failed to send invitation', 'Hindi naipadala ang invitation');
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  const hireLabel = sent
    ? t('Invitation sent', 'Naipadala na ang invitation')
    : unavailable
      ? t('Currently hired', 'Kasalukuyang hired')
      : needsVerification
        ? t('Verify to hire', 'I-verify para makapag-hire')
        : t('Hire this worker', 'I-hire ang worker');

  const messageLabel = needsVerification
    ? t('Verify to message', 'I-verify para makapag-message')
    : t('Message', 'Mag-message');

  return (
    <div className={cn('space-y-2.5', className)}>
      <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-1">
        <Button
          type="button"
          className="worker-cta-amber h-11 w-full gap-2 rounded-none"
          size="lg"
          disabled={unavailable || sent || loading}
          onClick={openHireFlow}
        >
          <Handshake className="h-5 w-5 shrink-0" />
          {hireLabel}
        </Button>
        <Button
          type="button"
          variant="outline"
          className={cn(
            'h-11 w-full gap-2 rounded-none',
            onDark
              ? 'border-white/30 bg-white/10 text-white hover:bg-white/15 hover:text-white'
              : 'border-[#d6d0c4] bg-white text-[var(--home-ink)] hover:border-[var(--home-ink)] hover:bg-[var(--home-sand)]/40'
          )}
          size="lg"
          onClick={openMessage}
        >
          <MessageCircle className="h-5 w-5 shrink-0" />
          {messageLabel}
        </Button>
      </div>

      {needsVerification && (
        <p className={cn('text-sm', onDark ? 'text-amber-200' : 'text-amber-800')}>
          {t(
            'Verify your identity to hire or message this worker.',
            'I-verify ang identity mo para makapag-hire o mag-message sa worker na ito.'
          )}
        </p>
      )}

      {error && (
        <div className="space-y-2">
          <p className={cn('text-sm', onDark ? 'text-amber-200' : 'text-amber-800')}>{error}</p>
          {needsVerification && (
            <Link href="/customer/verification" className="inline-flex">
              <Button
                type="button"
                size="sm"
                variant="outline"
                className={cn(
                  'gap-1.5 rounded-none',
                  onDark
                    ? 'border-white/30 bg-white/10 text-white hover:bg-white/15 hover:text-white'
                    : 'border-amber-300 bg-amber-50 text-amber-900'
                )}
              >
                <ShieldCheck className="h-4 w-4" />
                {t('Go to verification', 'Pumunta sa verification')}
              </Button>
            </Link>
          )}
        </div>
      )}
      {sent && (
        <p className={cn('text-sm', onDark ? 'text-slate-300' : 'text-slate-600')}>
          {t(
            'Invitation sent. The worker can accept or reject your offer.',
            'Naipadala ang invitation. Puwedeng i-accept o i-reject ng worker ang offer mo.'
          )}
        </p>
      )}

      <HireDisclaimerModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onConfirm={sendInvitation}
        workerName={workerName}
        intent="send-hire-invite"
        loading={loading}
      />
    </div>
  );
}
