'use client';

import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Download, MessageSquare } from 'lucide-react';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { Input } from '@/components/ui/shared/Input';
import { CaseToothChartPanel } from '@/components/ui/lab/CaseToothChartPanel';
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import { LabCaseAttachmentPreview } from '@/components/ui/lab/LabCaseAttachmentPreview';
import { LabCaseAttachmentsDialog } from '@/components/ui/lab/LabCaseAttachmentsDialog';
import {
  LabCaseShareQrDialog,
  LabCaseShareQrThumb,
} from '@/components/ui/lab/LabCaseShareQrDialog';
import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import { formatToothList } from '@/components/treatment/prosthesisTypeDisplay';
import { ProsthesisStackedTypeLabel } from '@/components/ui/lab/ProsthesisStackedTypeLabel';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import {
  buildCaseConnectedTeeth,
  buildCaseProsthesisRows,
  formatCaseDateTime,
  formatPatientName,
  latestCaseAttachment,
} from '@/components/lab/caseDetailUtils';
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge';
import { useToast } from '@/lib/hooks/useToast';
import type { AssignableTaskStaff, LabCaseDetail, LabTaskStatus } from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';

function CaseTaskProgressBar({ 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>
  );
}

export interface CaseDetailPanelProps {
  labCase: LabCaseDetail;
  locale: string;
  treatmentLabel: (type: string) => string;
  statusOptions: { value: LabTaskStatus; label: string }[];
  loadAttachmentBlob: (caseId: string, attachmentId: string) => Promise<Blob>;
  /** Extra lines below patient mobile (e.g. connection-specific clinic/lab line). */
  headerMetaLines?: ReactNode;
  showCommentsButton?: boolean;
  commentCount?: number;
  onCommentsClick?: () => void;
  canEditImportant?: boolean;
  updatingImportant?: boolean;
  onImportantChange?: (checked: boolean) => void;
  updatingExternalCode?: boolean;
  onExternalCodeChange?: (externalCode: string | null) => void;
  commentsSection?: ReactNode;
  assignableStaff?: AssignableTaskStaff[];
  canAssignTasks?: boolean;
  assigningTaskId?: string | null;
  onAssignTask?: (taskId: string, assigneeUserId: string | null) => void;
}

export function CaseDetailPanel({
  labCase,
  locale,
  treatmentLabel,
  statusOptions,
  loadAttachmentBlob,
  headerMetaLines,
  showCommentsButton = false,
  commentCount = 0,
  onCommentsClick,
  canEditImportant = false,
  updatingImportant = false,
  onImportantChange,
  updatingExternalCode = false,
  onExternalCodeChange,
  commentsSection,
  assignableStaff = [],
  canAssignTasks = false,
  assigningTaskId = null,
  onAssignTask,
}: CaseDetailPanelProps) {
  const t = useTranslations('cases');
  const tTreatment = useTranslations('treatment');
  const intlLocale = useLocale();
  const toast = useToast();
  const [attachmentsDialogOpen, setAttachmentsDialogOpen] = useState(false);
  const [shareQrDialogOpen, setShareQrDialogOpen] = useState(false);
  const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
  const [downloadingPdf, setDownloadingPdf] = useState(false);
  const [externalCodeDraft, setExternalCodeDraft] = useState(labCase.externalCode ?? '');

  useEffect(() => {
    setExternalCodeDraft(labCase.externalCode ?? '');
  }, [labCase.id, labCase.externalCode]);

  useEffect(() => {
    void prosthesisCatalogApi
      .list()
      .then((response) => setProsthesisCatalog(response.data))
      .catch(() => {});
  }, []);

  const prosthesisRows = useMemo(() => buildCaseProsthesisRows(labCase), [labCase]);
  const connectedTeeth = useMemo(() => buildCaseConnectedTeeth(labCase), [labCase]);
  const previewAttachment = useMemo(() => latestCaseAttachment(labCase), [labCase]);

  async function handleDownloadCaseSheet() {
    setDownloadingPdf(true);
    try {
      await downloadCaseSheetPdf({
        labCase,
        locale: intlLocale,
        prosthesisCatalog,
        labels: {
          title: t('caseSheetTitle'),
          orderNumber: t('caseSheetOrderNumber'),
          orderDate: t('caseSheetOrderDate'),
          dateDue: t('caseSheetDateDue'),
          sender: t('caseSheetSender'),
          recipient: t('caseSheetRecipient'),
          patient: t('caseSheetPatient'),
          patientId: t('caseSheetPatientId'),
          prosthesis: t('caseSheetProsthesis'),
          toothChart: t('caseSheetToothChart'),
          connected: tTreatment('connectedBadge'),
          teeth: t('teethLabel'),
          archUpper: tTreatment('selectedArchUpper'),
          archLower: tTreatment('selectedArchLower'),
          comments: t('caseSheetComments'),
          noComments: t('caseSheetNoComments'),
        },
      });
    } catch {
      toast.showError(t('errorDownloadCaseSheet'));
    } finally {
      setDownloadingPdf(false);
    }
  }

  return (
    <div className="space-y-4">
      <header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between border-b border-border pb-3">
        <div className="min-w-0 flex-1 space-y-1">
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-lg font-semibold text-text-primary">
              {formatPatientName(labCase.patient)}
            </h2>
            <LabCaseDueDateBadge dueDate={labCase.dueDate} locale={locale} />
            <LabCaseOriginBadge origin={labCase.origin} />
          </div>
          {!canEditImportant && labCase.isImportant ? (
            <Badge variant="warning" fixedWidth={false} className="mt-1">
              {t('importantLabel')}
            </Badge>
          ) : null}
          <p className="text-sm text-text-muted">
            {t('patientMobile')}: {labCase.patient.mobile}
          </p>
          {headerMetaLines}
          <p className="text-sm text-text-muted">
            {t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })}
          </p>
          <div className="pt-1 max-w-xs">
            <p className="text-sm text-text-muted mb-1">
              {t('taskProgressLabel', {
                completed: labCase.taskProgress.completed,
                total: labCase.taskProgress.total,
              })}
            </p>
            <CaseTaskProgressBar
              completed={labCase.taskProgress.completed}
              total={labCase.taskProgress.total}
            />
          </div>
        </div>

        <div className="flex w-full sm:w-auto shrink-0 flex-col items-end gap-2">
          {canEditImportant ? (
            <div className="flex w-full max-w-sm items-center gap-3">
              <Checkbox
                checked={labCase.isImportant ?? false}
                disabled={updatingImportant}
                label={t('markCaseImportant')}
                labelPosition="start"
                className="shrink-0"
                onChange={(checked) => onImportantChange?.(checked)}
              />
              <div className="min-w-0 flex-1">
                <Input
                  value={externalCodeDraft}
                  placeholder={t('externalCodePlaceholder')}
                  disabled={updatingExternalCode}
                  maxLength={64}
                  aria-label={t('externalCodePlaceholder')}
                  onChange={(e) => setExternalCodeDraft(e.target.value)}
                  onBlur={() => {
                    const next = externalCodeDraft.trim() || null;
                    const prev = labCase.externalCode?.trim() || null;
                    if (next === prev) return;
                    onExternalCodeChange?.(next);
                  }}
                />
              </div>
            </div>
          ) : labCase.externalCode?.trim() ? (
            <p className="text-sm text-text-muted">{labCase.externalCode.trim()}</p>
          ) : null}
          <div className="flex w-full sm:w-auto flex-wrap items-center justify-end gap-2">
            {showCommentsButton && onCommentsClick ? (
              <Button type="button" variant="outline" size="sm" onClick={onCommentsClick}>
                <MessageSquare className="h-4 w-4 me-1.5" />
                {commentCount > 0
                  ? t('commentsCount', { count: commentCount })
                  : t('showComments')}
              </Button>
            ) : null}
            <Button
              type="button"
              variant="outline"
              size="sm"
              isLoading={downloadingPdf}
              onClick={() => void handleDownloadCaseSheet()}
            >
              <Download className="h-4 w-4 me-1.5" />
              {t('downloadCaseSheet')}
            </Button>
          </div>
          {labCase.shareUrl || (previewAttachment && labCase.attachments.length > 0) ? (
            <div className="flex flex-row items-center gap-2 shrink-0">
              {previewAttachment && labCase.attachments.length > 0 ? (
                <button
                  type="button"
                  onClick={() => setAttachmentsDialogOpen(true)}
                  className="aspect-square w-24 sm:w-32 cursor-pointer rounded-[var(--radius-md)] border border-border/60 overflow-hidden transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
                  title={previewAttachment.fileName}
                  aria-label={t('viewAttachments')}
                >
                  <LabCaseAttachmentPreview
                    caseId={labCase.id}
                    attachment={previewAttachment}
                    loadBlob={loadAttachmentBlob}
                    className="h-full w-full"
                  />
                </button>
              ) : null}
              {labCase.shareUrl ? (
                <LabCaseShareQrThumb
                  shareUrl={labCase.shareUrl}
                  onClick={() => setShareQrDialogOpen(true)}
                />
              ) : null}
            </div>
          ) : null}
        </div>
      </header>

      <CaseToothChartPanel
        details={labCase.detail ? [{ teeth: labCase.detail.teeth }] : []}
        prosthesisRows={prosthesisRows}
        connectedTeeth={connectedTeeth}
        prosthesisCatalog={prosthesisCatalog}
        className="w-full"
      />

      {labCase.detail ? (
        <div className="space-y-2">
          <h3 className="text-sm font-medium text-text-primary">{t('treatmentDetails')}</h3>
          <div className="rounded-md bg-background border border-border p-2 text-sm">
            <div className="font-medium">{treatmentLabel(labCase.detail.treatmentType)}</div>
            <div className="flex flex-wrap items-center gap-2 text-text-muted">
              <span>
                {t('teethLabel')}: {labCase.detail.teeth.join(', ') || '—'}
              </span>
              {connectedTeeth.size > 0 ? <ConnectedSelectionBadge /> : null}
            </div>
            {labCase.detail.comment ? (
              <div className="text-text-muted mt-1">{labCase.detail.comment}</div>
            ) : null}
          </div>
        </div>
      ) : null}

      <div className="space-y-3">
        <h3 className="text-sm font-medium text-text-primary">{t('tasksByTooth')}</h3>
        {labCase.tasksByTooth.length === 0 ? (
          <p className="text-sm text-text-muted">{t('noTasks')}</p>
        ) : (
          labCase.tasksByTooth.map((group) => (
            <div
              key={`${group.treatmentDetailId}-${group.selectionGroupId ?? ''}-${group.prosthesisTypeCode}`}
              className="rounded-md border border-border p-3 space-y-2"
            >
              <div className="flex flex-wrap items-center gap-2">
                <ProsthesisStackedTypeLabel
                  className="min-w-0 whitespace-normal break-words text-sm font-medium"
                  code={group.prosthesisTypeCode}
                  catalog={prosthesisCatalog}
                />
                <span className="text-sm text-text-secondary">
                  {formatToothList(group.teeth, {
                    UA: tTreatment('selectedArchUpper'),
                    LA: tTreatment('selectedArchLower'),
                  })}
                </span>
                {group.connected ? <ConnectedSelectionBadge /> : null}
              </div>
              <ul className="space-y-2">
                {group.tasks.map((task) => (
                  <li key={task.id} className="rounded bg-background px-2 py-1.5 text-sm">
                    <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                      <span className="min-w-0 flex-1 font-medium text-text-primary">
                        {task.stepOrder}. {task.stepLabel}
                      </span>
                      <span className="text-[11px] text-text-muted shrink-0">
                        {task.lastStatusChangedBy
                          ? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
                          : t('lastUpdatedUnknown')}
                        {task.lastStatusChangedAt
                          ? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
                          : ''}
                      </span>
                      {canAssignTasks && onAssignTask ? (
                        <select
                          value={task.assignee?.id ?? ''}
                          disabled={assigningTaskId === task.id}
                          onChange={(e) =>
                            onAssignTask(task.id, e.target.value ? e.target.value : null)
                          }
                          aria-label={t('assigneeLabel')}
                          className={`${FORM_SELECT_CLASS} max-w-[9.5rem] rounded-md py-0.5 text-xs`}
                        >
                          <option value="">{t('assigneeUnassigned')}</option>
                          {assignableStaff.map((staff) => (
                            <option key={staff.id} value={staff.id}>
                              {staff.name}
                            </option>
                          ))}
                        </select>
                      ) : null}
                      <Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
                        {statusOptions.find((opt) => opt.value === task.status)?.label ??
                          task.status}
                      </Badge>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          ))
        )}
      </div>

      {commentsSection}

      <LabCaseAttachmentsDialog
        open={attachmentsDialogOpen}
        onClose={() => setAttachmentsDialogOpen(false)}
        caseId={labCase.id}
        attachments={labCase.attachments}
        loadBlob={loadAttachmentBlob}
      />

      {labCase.shareUrl ? (
        <LabCaseShareQrDialog
          open={shareQrDialogOpen}
          onClose={() => setShareQrDialogOpen(false)}
          shareUrl={labCase.shareUrl}
        />
      ) : null}
    </div>
  );
}

export { CaseTaskProgressBar };
