import { Link } from 'react-router-dom';
import { Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { extractApiError } from '@/api/client';
import type { Engagement } from '@/api/types';
import { useDeleteEngagement, useEngagementsList } from '@/hooks/useEngagements';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/useToast';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { EmptyState } from '@/components/EmptyState';
import { StatusBadge } from '@/components/StatusBadge';
import { formatDate } from '@/lib/format';

export function EngagementsListPage(): JSX.Element {
  const { t } = useTranslation();
  const { data, isLoading, isError, error, refetch } = useEngagementsList();
  const { canEditEngagements } = useAuth();
  const { push } = useToast();
  const deleteMutation = useDeleteEngagement();

  const onDelete = async (eng: Engagement) => {
    if (!window.confirm(t('engagement.list.deleteConfirm', { name: eng.name }))) return;
    try {
      await deleteMutation.mutateAsync(eng.id);
      push(t('engagement.list.toast.deleted'), 'success');
    } catch (err) {
      push(extractApiError(err, t('engagement.list.error.delete')), 'error');
    }
  };

  return (
    <div className="flex flex-col gap-xl">
      <header className="flex items-end justify-between gap-md">
        <div>
          <h1 className="text-[32px] font-medium leading-none">{t('engagement.list.title')}</h1>
          <p className="text-charcoal text-[16px] mt-sm">
            {t('engagement.list.subtitle')}
          </p>
        </div>
        {canEditEngagements ? (
          <Link to="/engagements/new" className="btn-primary">
            <Plus size={14} aria-hidden /> {t('engagement.list.new')}
          </Link>
        ) : null}
      </header>

      {isLoading ? <LoadingState label={t('common.loading')} /> : null}

      {isError ? (
        <ErrorState message={extractApiError(error, t('engagement.list.error.load'))} onRetry={() => refetch()} />
      ) : null}

      {!isLoading && !isError && data && data.length === 0 ? (
        <EmptyState
          title={t('engagement.list.empty.title')}
          description={t('engagement.list.empty.desc')}
          action={
            canEditEngagements ? (
              <Link to="/engagements/new" className="btn-primary">
                <Plus size={14} aria-hidden /> {t('engagement.list.new')}
              </Link>
            ) : undefined
          }
        />
      ) : null}

      {!isLoading && !isError && data && data.length > 0 ? (
        <div className="card-product overflow-hidden p-0">
          <table className="table-compact w-full text-left">
            <thead className="bg-cloud border-b border-hairline">
              <tr>
                <th>{t('engagement.list.col.name')}</th>
                <th>{t('engagement.list.col.status')}</th>
                <th>{t('engagement.list.col.start')}</th>
                <th>{t('engagement.list.col.end')}</th>
                <th>{t('engagement.list.col.createdBy')}</th>
                <th className="text-right">{t('engagement.list.col.actions')}</th>
              </tr>
            </thead>
            <tbody>
              {data.map((eng) => (
                <tr key={eng.id}>
                  <td>
                    <Link to={`/engagements/${eng.id}`} className="text-ink font-medium hover:underline">
                      {eng.name}
                    </Link>
                  </td>
                  <td>
                    <StatusBadge status={eng.status} />
                  </td>
                  <td className="text-charcoal font-mono">{formatDate(eng.start_date)}</td>
                  <td className="text-charcoal font-mono">{formatDate(eng.end_date)}</td>
                  <td className="text-charcoal">{eng.created_by.username}</td>
                  <td className="text-right">
                    <div className="inline-flex gap-sm">
                      <Link to={`/engagements/${eng.id}`} className="btn-text-link">
                        {t('engagement.list.view')}
                      </Link>
                      {canEditEngagements ? (
                        <>
                          <Link to={`/engagements/${eng.id}/edit`} className="btn-text-link">
                            {t('engagement.list.edit')}
                          </Link>
                          <button
                            type="button"
                            className="btn-text-link text-bloom-deep"
                            onClick={() => onDelete(eng)}
                            disabled={deleteMutation.isPending}
                          >
                            {t('engagement.list.delete')}
                          </button>
                        </>
                      ) : null}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}
