import { useParams, Link } from 'react-router-dom';
import { extractApiError } from '@/api/client';
import { useAuth } from '@/hooks/useAuth';
import { useEngagement } from '@/hooks/useEngagements';
import { useHashTab } from '@/hooks/useHashTab';
import { useEngagementSimulations } from '@/hooks/useSimulations';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { StatusBadge } from '@/components/StatusBadge';
import { SimulationList } from '@/components/SimulationList';
import { ExportEngagementButton } from '@/components/ExportEngagementButton';
import { BackLink } from '@/components/BackLink';
import { Tabs } from '@/components/Tabs';

type TabId = 'description' | 'simulations';

export function EngagementDetailPage(): JSX.Element {
  const { id } = useParams<{ id: string }>();
  const numericId = id ? Number(id) : undefined;
  const { canEditEngagements } = useAuth();

  const detail = useEngagement(numericId);
  const simsQuery = useEngagementSimulations(numericId);

  const [activeTabRaw, setActiveTab] = useHashTab('description');
  const activeTab = activeTabRaw as TabId;

  if (detail.isLoading) return <LoadingState label="Loading engagement…" />;
  if (detail.isError) {
    return (
      <ErrorState
        message={extractApiError(detail.error, 'Could not load engagement')}
        onRetry={() => detail.refetch()}
      />
    );
  }
  if (!detail.data) return <ErrorState message="Engagement not found" />;

  const eng = detail.data;
  const simCount = simsQuery.data?.length;

  const tabs = [
    { id: 'description', label: 'Description' },
    { id: 'simulations', label: 'Simulations', count: simCount },
  ];

  return (
    <div className="flex flex-col gap-xl">
      <header className="flex items-start justify-between gap-md">
        <div className="flex flex-col gap-sm">
          <BackLink to="/engagements">Back to engagements</BackLink>
          <h1 className="text-[32px] font-medium leading-none">{eng.name}</h1>
          <div className="flex items-center gap-md">
            <StatusBadge status={eng.status} />
            <span className="text-[14px] text-graphite">
              Created by <span className="text-ink">{eng.created_by.username}</span>
            </span>
          </div>
        </div>
        {canEditEngagements ? (
          <ExportEngagementButton engagementId={eng.id} />
        ) : null}
      </header>

      <Tabs items={tabs} activeId={activeTab} onChange={setActiveTab} />

      <div
        role="tabpanel"
        id={`tabpanel-${activeTab}`}
        aria-labelledby={`tab-${activeTab}`}
      >
        {activeTab === 'description' && (
          <div className="card-product flex flex-col gap-md">
            <header className="flex items-start justify-between gap-md">
              <dl className="grid grid-cols-2 gap-x-lg gap-y-xxs text-caption-md">
                <dt className="text-graphite">Start date</dt>
                <dd className="font-mono">{eng.start_date}</dd>
                <dt className="text-graphite">End date</dt>
                <dd className="font-mono">{eng.end_date ?? '—'}</dd>
                <dt className="text-graphite">Status</dt>
                <dd><StatusBadge status={eng.status} /></dd>
                <dt className="text-graphite">Created at</dt>
                <dd className="font-mono">{eng.created_at}</dd>
              </dl>
              {canEditEngagements ? (
                <Link to={`/engagements/${eng.id}/edit`} className="btn-outline shrink-0">
                  Edit
                </Link>
              ) : null}
            </header>
            <hr className="border-hairline" />
            <h2 className="text-display-sm">Description</h2>
            <p className="text-[16px] text-charcoal whitespace-pre-line">
              {eng.description?.trim() ? eng.description : 'No description provided.'}
            </p>
          </div>
        )}

        {activeTab === 'simulations' && (
          <SimulationList engagementId={eng.id} />
        )}
      </div>
    </div>
  );
}
