'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { useToast } from '@/lib/hooks/useToast';
import { organizationApi } from '@/lib/api/organization';
import { Badge, type BadgeVariant } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { ToastStack } from '@/components/ui/shared/Toast';
import type { CounterpartItemDto } from '@/lib/api/organization';
import type { LabCaseDetail, LabCaseListItem, LabTaskStatus } from '@/types/cases';

const TREATMENT_TYPE_KEYS = {
  consultation: 'typeConsultation',
  filling: 'typeFilling',
  endo: 'typeEndo',
  visit: 'typeVisit',
  hygiene: 'typeHygiene',
} as const;

const PAGE_SIZE = 20;

function taskStatusVariant(status: LabTaskStatus): BadgeVariant {
  switch (status) {
    case 'COMPLETED':
      return 'success';
    case 'IN_PROGRESS':
      return 'default';
    default:
      return 'warning';
  }
}

function formatPatientName(patient: { firstName: string; lastName: string }) {
  return `${patient.firstName} ${patient.lastName}`.trim();
}

function formatDateTime(value: string | null, locale: string) {
  if (!value) return '—';
  return new Intl.DateTimeFormat(locale, {
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(new Date(value));
}

function TaskProgressBar({ completed, total }: { completed: number; total: number }) {
  const pct = total > 0 ? Math.round((completed / total) * 100) : 0;

  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-xs text-text-muted">
        <span>
          {completed}/{total}
        </span>
        <span>{pct}%</span>
      </div>
      <div className="h-1.5 rounded-full bg-border overflow-hidden">
        <div
          className="h-full rounded-full bg-primary transition-all duration-300"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}

interface ConnectionCaseHistoryContentProps {
  connection: CounterpartItemDto;
  onBack: () => void;
}

export function ConnectionCaseHistoryContent({
  connection,
  onBack,
}: ConnectionCaseHistoryContentProps) {
  const t = useTranslations('organizations');
  const tCases = useTranslations('cases');
  const tTreatment = useTranslations('treatment');
  const tCommon = useTranslations('common');
  const { currentOrganization, user } = useAuth();
  const { showError, setError, messages: toastMessages } = useToast();

  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [cases, setCases] = useState<LabCaseListItem[]>([]);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: PAGE_SIZE,
    total: 0,
    totalPages: 1,
  });
  const [selectedCaseId, setSelectedCaseId] = useState<string | null>(null);
  const [selectedCase, setSelectedCase] = useState<LabCaseDetail | null>(null);
  const [loadingList, setLoadingList] = useState(false);
  const [loadingDetail, setLoadingDetail] = useState(false);

  const locale = user?.language ?? 'en';
  const isClinic = currentOrganization?.type === 'CLINIC';

  const tRef = useRef(t);
  tRef.current = t;

  const treatmentLabel = useCallback(
    (type: string) => {
      const key = TREATMENT_TYPE_KEYS[type as keyof typeof TREATMENT_TYPE_KEYS];
      return key ? tTreatment(key) : type;
    },
    [tTreatment],
  );

  const statusOptions: { value: LabTaskStatus; label: string }[] = useMemo(
    () => [
      { value: 'PENDING', label: tCases('statusPending') },
      { value: 'IN_PROGRESS', label: tCases('statusInProgress') },
      { value: 'COMPLETED', label: tCases('statusCompleted') },
    ],
    [tCases],
  );

  useEffect(() => {
    let cancelled = false;

    const timeout = setTimeout(() => {
      void (async () => {
        setLoadingList(true);
        setError('');
        try {
          const response = await organizationApi.listConnectionCases(connection.id, {
            q: search.trim() || undefined,
            page,
            limit: PAGE_SIZE,
          });
          if (cancelled) return;
          setCases(response.data.items);
          setPagination(response.data.pagination);
        } catch (error: unknown) {
          if (cancelled) return;
          showError(formatApiErrorMessage(error, tRef.current('caseHistoryErrorLoadList')));
        } finally {
          if (!cancelled) setLoadingList(false);
        }
      })();
    }, search ? 300 : 0);

    return () => {
      cancelled = true;
      clearTimeout(timeout);
    };
  }, [search, page, connection.id, showError, setError]);

  useEffect(() => {
    if (!selectedCaseId) {
      setSelectedCase(null);
      return;
    }

    let cancelled = false;

    void (async () => {
      setLoadingDetail(true);
      setError('');
      try {
        const response = await organizationApi.getConnectionCase(connection.id, selectedCaseId);
        if (cancelled) return;
        setSelectedCase(response.data);
      } catch (error: unknown) {
        if (cancelled) return;
        showError(formatApiErrorMessage(error, tRef.current('caseHistoryErrorLoadDetail')));
        setSelectedCase(null);
      } finally {
        if (!cancelled) setLoadingDetail(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [selectedCaseId, connection.id, showError, setError]);

  return (
    <div className="space-y-6">
      <div>
        <button
          type="button"
          onClick={onBack}
          className="text-sm text-primary hover:opacity-90"
        >
          {t('caseHistoryBackToConnections')}
        </button>
      </div>

      <div>
        <h1 className="text-2xl font-semibold text-text-primary">
          {t('caseHistoryTitle', { name: connection.organizationName })}
        </h1>
        <p className="text-sm text-text-secondary mt-1">
          {isClinic ? t('caseHistorySubtitleClinic') : t('caseHistorySubtitleLab')}
        </p>
      </div>

      <ToastStack {...toastMessages} />

      <div className="grid gap-4 lg:grid-cols-[minmax(300px,380px)_1fr]">
        <section className="rounded-lg border border-border bg-surface p-4 space-y-3 flex flex-col min-h-0">
          <SearchBar
            embedded
            value={search}
            onChange={(value) => {
              setSearch(value);
              setPage(1);
            }}
            placeholder={tCases('searchPlaceholder')}
          />

          <div className="flex-1 min-h-0">
            {loadingList ? (
              <p className="text-sm text-text-muted">{tCommon('loading')}</p>
            ) : cases.length === 0 ? (
              <p className="text-sm text-text-muted">{t('caseHistoryEmpty')}</p>
            ) : (
              <ul className="space-y-2 max-h-[55vh] overflow-y-auto pr-1">
                {cases.map((item) => {
                  const isActive = item.id === selectedCaseId;

                  return (
                    <li key={item.id}>
                      <button
                        type="button"
                        onClick={() => setSelectedCaseId(item.id)}
                        className={`w-full rounded-md border px-3 py-2.5 text-left transition-colors ${
                          isActive
                            ? 'border-primary bg-primary/5'
                            : 'border-border hover:border-primary/40'
                        }`}
                      >
                        <div className="font-medium text-text-primary">
                          {formatPatientName(item.patient)}
                        </div>
                        <div className="text-xs text-text-muted mt-0.5">{item.patient.mobile}</div>
                        {!isClinic ? (
                          <div className="text-xs text-text-muted mt-0.5">{item.clinic.name}</div>
                        ) : null}
                        <div className="text-xs text-text-muted mt-1">
                          {formatDateTime(item.sentAt, locale)}
                        </div>
                        <div className="text-xs text-text-muted mt-1 truncate">
                          {item.treatmentTypes.map(treatmentLabel).join(', ')}
                        </div>
                        <div className="mt-2">
                          <TaskProgressBar
                            completed={item.taskProgress.completed}
                            total={item.taskProgress.total}
                          />
                        </div>
                      </button>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>

          {pagination.totalPages > 1 ? (
            <div className="flex items-center justify-between gap-2 pt-2 border-t border-border">
              <Button
                variant="outline"
                size="sm"
                disabled={page <= 1 || loadingList}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
              >
                {tCases('prevPage')}
              </Button>
              <span className="text-xs text-text-muted text-center">
                {tCases('pageSummary', {
                  page: pagination.page,
                  totalPages: pagination.totalPages,
                  total: pagination.total,
                })}
              </span>
              <Button
                variant="outline"
                size="sm"
                disabled={page >= pagination.totalPages || loadingList}
                onClick={() => setPage((p) => p + 1)}
              >
                {tCases('nextPage')}
              </Button>
            </div>
          ) : null}
        </section>

        <section className="rounded-lg border border-border bg-surface p-4 min-h-[420px]">
          {!selectedCaseId ? (
            <p className="text-sm text-text-muted">{tCases('selectCaseHint')}</p>
          ) : loadingDetail || !selectedCase ? (
            <p className="text-sm text-text-muted">{tCommon('loading')}</p>
          ) : (
            <div className="space-y-4">
              <header className="space-y-1 border-b border-border pb-3">
                <h2 className="text-lg font-semibold text-text-primary">
                  {formatPatientName(selectedCase.patient)}
                </h2>
                <p className="text-sm text-text-muted">
                  {tCases('patientMobile')}: {selectedCase.patient.mobile}
                </p>
                {!isClinic ? (
                  <p className="text-sm text-text-muted">
                    {tCases('fromClinic', { name: selectedCase.clinic.name })}
                  </p>
                ) : (
                  <p className="text-sm text-text-muted">
                    {t('caseHistorySentToLab', { name: connection.organizationName })}
                  </p>
                )}
                <p className="text-sm text-text-muted">
                  {tCases('sentAt', { date: formatDateTime(selectedCase.sentAt, locale) })}
                </p>
                <div className="pt-1 max-w-xs">
                  <p className="text-sm text-text-muted mb-1">
                    {tCases('taskProgressLabel', {
                      completed: selectedCase.taskProgress.completed,
                      total: selectedCase.taskProgress.total,
                    })}
                  </p>
                  <TaskProgressBar
                    completed={selectedCase.taskProgress.completed}
                    total={selectedCase.taskProgress.total}
                  />
                </div>
                {selectedCase.labComment ? (
                  <p className="text-sm text-text-muted pt-1">
                    <span className="font-medium text-text-primary">{tCases('labComment')}:</span>{' '}
                    {selectedCase.labComment}
                  </p>
                ) : null}
              </header>

              {selectedCase.details.length > 0 && (
                <div className="space-y-2">
                  <h3 className="text-sm font-medium text-text-primary">
                    {tCases('treatmentDetails')}
                  </h3>
                  <ul className="space-y-2 text-sm">
                    {selectedCase.details.map((detail) => (
                      <li
                        key={detail.id}
                        className="rounded-md bg-background border border-border p-2"
                      >
                        <div className="font-medium">{treatmentLabel(detail.treatmentType)}</div>
                        <div className="text-text-muted">
                          {tCases('teethLabel')}: {detail.teeth.join(', ') || '—'}
                        </div>
                        {detail.comment ? (
                          <div className="text-text-muted mt-1">{detail.comment}</div>
                        ) : null}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              <div className="space-y-3">
                <h3 className="text-sm font-medium text-text-primary">{tCases('tasksByTooth')}</h3>
                {selectedCase.tasksByTooth.length === 0 ? (
                  <p className="text-sm text-text-muted">{tCases('noTasks')}</p>
                ) : (
                  selectedCase.tasksByTooth.map((group) => (
                    <div
                      key={`${group.tooth}-${group.treatmentType}`}
                      className="rounded-md border border-border p-3 space-y-2"
                    >
                      <div className="text-sm font-medium text-text-primary">
                        {tCases('toothGroupTitle', {
                          tooth: group.tooth,
                          type: treatmentLabel(group.treatmentType),
                        })}
                      </div>
                      <ul className="space-y-2">
                        {group.tasks.map((task) => (
                          <li
                            key={task.id}
                            className="flex flex-wrap items-center gap-2 text-sm rounded bg-background p-2"
                          >
                            <span className="min-w-0 flex-1">
                              {task.stepOrder}. {task.stepLabel}
                            </span>
                            <Badge variant={taskStatusVariant(task.status)} fixedWidth={false}>
                              {statusOptions.find((opt) => opt.value === task.status)?.label ??
                                task.status}
                            </Badge>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))
                )}
              </div>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}
