'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { Check, Handshake, X } from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  PortalEmpty,
  PortalLoading,
  PortalShell,
} from '@/components/portal/Portal';
import { api, ApiError } from '@/lib/api';
import { formatDate } from '@/lib/utils';
import { useLanguage } from '@/contexts/LanguageContext';
import { getUploadUrl } from '@/lib/api';

type HireStatus = 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'CANCELLED' | 'COMPLETED';

interface HireInvitation {
  id: string;
  status: HireStatus;
  message?: string | null;
  createdAt: string;
  respondedAt?: string | null;
  customer: {
    id: string;
    firstName: string;
    lastName: string;
    avatarUrl?: string | null;
  };
  worker: {
    id: string;
    user: {
      id: string;
      firstName: string;
      lastName: string;
      avatarUrl?: string | null;
    };
  };
  review?: { id: string } | null;
}

interface HireInvitationsPageProps {
  role: 'customer' | 'worker';
}

const STATUS_STYLES: Record<HireStatus, string> = {
  PENDING: 'bg-amber-100 text-amber-900',
  ACCEPTED: 'bg-emerald-100 text-emerald-900',
  REJECTED: 'bg-rose-100 text-rose-900',
  CANCELLED: 'bg-slate-100 text-slate-600',
  COMPLETED: 'bg-slate-100 text-slate-700',
};

export function HireInvitationsPage({ role }: HireInvitationsPageProps) {
  const { t } = useLanguage();
  const [items, setItems] = useState<HireInvitation[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionId, setActionId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    api<{ data: HireInvitation[] }>('/hire-invitations?limit=50')
      .then((res) => setItems(res.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const runAction = async (id: string, action: 'accept' | 'reject' | 'cancel' | 'complete') => {
    setActionId(id);
    setError(null);
    try {
      await api(`/hire-invitations/${id}/${action}`, { method: 'PATCH' });
      load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Action failed');
    } finally {
      setActionId(null);
    }
  };

  return (
    <DashboardLayout
      role={role}
      title={t('Hire invitations', 'Mga hire invitation')}
    >
      <PortalShell>
        {error && <p className="text-sm text-rose-600">{error}</p>}

        {loading ? (
          <PortalLoading label={t('Loading invitations…', 'Naglo-load…')} />
        ) : items.length === 0 ? (
          <PortalEmpty
            icon={Handshake}
            title={t('No hire invitations yet', 'Wala pang hire invitation')}
            description={
              role === 'worker'
                ? t(
                    'When a customer wants to hire you, their invitation will appear here.',
                    'Kapag may customer na gustong mag-hire sa iyo, lalabas dito ang invitation.'
                  )
                : t(
                    'Send a hire invitation from a worker profile to get started.',
                    'Magpadala ng hire invitation mula sa worker profile para magsimula.'
                  )
            }
          />
        ) : (
          <div className="space-y-3">
            {items.map((item) => {
              const other =
                role === 'worker'
                  ? item.customer
                  : item.worker.user;
              const name = `${other.firstName} ${other.lastName}`;
              const busy = actionId === item.id;

              return (
                <div
                  key={item.id}
                  className="border border-[#e2ddd2] bg-white p-4"
                >
                  <div className="flex items-start gap-3">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={
                        other.avatarUrl
                          ? getUploadUrl(other.avatarUrl)
                          : `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=0c1929&color=fff`
                      }
                      alt=""
                      className="h-11 w-11 object-cover"
                    />
                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-2">
                        <p className="font-semibold text-slate-900">{name}</p>
                        <Badge className={`rounded-none ${STATUS_STYLES[item.status]}`}>
                          {item.status}
                        </Badge>
                      </div>
                      {item.message && (
                        <p className="mt-1 text-sm text-slate-600">{item.message}</p>
                      )}
                      <p className="mt-1 text-xs text-muted">{formatDate(item.createdAt)}</p>

                      {role === 'worker' && item.status === 'PENDING' && (
                        <div className="mt-3 flex flex-wrap gap-2">
                          <Button
                            size="sm"
                            className="worker-cta-amber rounded-none gap-1.5"
                            disabled={busy}
                            onClick={() => runAction(item.id, 'accept')}
                          >
                            <Check className="h-4 w-4" />
                            {t('Accept', 'Tanggapin')}
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            className="rounded-none gap-1.5"
                            disabled={busy}
                            onClick={() => runAction(item.id, 'reject')}
                          >
                            <X className="h-4 w-4" />
                            {t('Reject', 'Tanggihan')}
                          </Button>
                        </div>
                      )}

                      {role === 'customer' && item.status === 'PENDING' && (
                        <div className="mt-3">
                          <Button
                            size="sm"
                            variant="outline"
                            className="rounded-none"
                            disabled={busy}
                            onClick={() => runAction(item.id, 'cancel')}
                          >
                            {t('Cancel invitation', 'I-cancel ang invitation')}
                          </Button>
                        </div>
                      )}

                      {item.status === 'ACCEPTED' && (
                        <div className="mt-3 flex flex-wrap gap-2">
                          <Button
                            size="sm"
                            className="rounded-none"
                            disabled={busy}
                            onClick={() => runAction(item.id, 'complete')}
                          >
                            {t('Mark hire complete', 'Markahan bilang tapos')}
                          </Button>
                          {role === 'customer' && (
                            <Link href={`/workers/${item.worker.id}`}>
                              <Button size="sm" variant="outline" className="rounded-none">
                                {t('View profile', 'Tingnan ang profile')}
                              </Button>
                            </Link>
                          )}
                          {role === 'customer' && !item.review && (
                            <Link href="/customer/reviews">
                              <Button size="sm" variant="outline" className="rounded-none">
                                {t('Leave review', 'Mag-iwan ng review')}
                              </Button>
                            </Link>
                          )}
                        </div>
                      )}

                      {role === 'customer' && item.status === 'COMPLETED' && !item.review && (
                        <div className="mt-3">
                          <Link href="/customer/reviews">
                            <Button size="sm" className="worker-cta-amber rounded-none">
                              {t('Leave review', 'Mag-iwan ng review')}
                            </Button>
                          </Link>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </PortalShell>
    </DashboardLayout>
  );
}
