'use client';

import { useMemo, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { 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 { CaseToothChartPanel } from '@/components/ui/lab/CaseToothChartPanel';
import { LabCaseAttachmentPreview } from '@/components/ui/lab/LabCaseAttachmentPreview';
import { LabCaseAttachmentsDialog } from '@/components/ui/lab/LabCaseAttachmentsDialog';
import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
import {
  formatToothList,
  prosthesisTypeBadgeStyle,
} from '@/components/treatment/prosthesisTypeDisplay';
import {
  buildCaseProsthesisRows,
  formatCaseDateTime,
  formatPatientName,
  latestCaseAttachment,
} from '@/components/lab/caseDetailUtils';
import type { LabCaseDetail, LabTaskStatus } from '@/types/cases';

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;
  commentsSection?: ReactNode;
}

export function CaseDetailPanel({
  labCase,
  locale,
  treatmentLabel,
  statusOptions,
  loadAttachmentBlob,
  headerMetaLines,
  showCommentsButton = false,
  commentCount = 0,
  onCommentsClick,
  canEditImportant = false,
  updatingImportant = false,
  onImportantChange,
  commentsSection,
}: CaseDetailPanelProps) {
  const t = useTranslations('cases');
  const [attachmentsDialogOpen, setAttachmentsDialogOpen] = useState(false);

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

  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">
          <h2 className="text-lg font-semibold text-text-primary">
            {formatPatientName(labCase.patient)}
          </h2>
          {!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-row sm:flex-col items-center sm:items-end justify-between sm:justify-start 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}
          {canEditImportant ? (
            <Checkbox
              checked={labCase.isImportant ?? false}
              disabled={updatingImportant}
              label={t('markCaseImportant')}
              className="shrink-0"
              onChange={(checked) => onImportantChange?.(checked)}
            />
          ) : null}
          {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}
        </div>
      </header>

      <CaseToothChartPanel
        details={labCase.detail ? [{ teeth: labCase.detail.teeth }] : []}
        prosthesisRows={prosthesisRows}
        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="text-text-muted">
              {t('teethLabel')}: {labCase.detail.teeth.join(', ') || '—'}
            </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, groupIndex) => (
            <div
              key={`${group.treatmentDetailId}-${group.prosthesisTypeCode}`}
              className="rounded-md border border-border p-3 space-y-2"
            >
              <div className="flex flex-wrap items-center gap-2">
                <Badge
                  truncate
                  title={group.prosthesisTypeLabel}
                  style={prosthesisTypeBadgeStyle(group.prosthesisTypeCode, groupIndex)}
                >
                  {group.prosthesisTypeLabel}
                </Badge>
                <span className="text-sm font-medium text-text-primary">
                  {t('toothGroupTitle', {
                    teeth: formatToothList(group.teeth),
                    prosthesis: group.prosthesisTypeLabel,
                  })}
                </span>
              </div>
              <ul className="space-y-2">
                {group.tasks.map((task) => (
                  <li key={task.id} className="rounded bg-background p-2 text-sm space-y-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="min-w-0 flex-1">
                        {task.stepOrder}. {task.stepLabel}
                      </span>
                      <Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
                        {statusOptions.find((opt) => opt.value === task.status)?.label ??
                          task.status}
                      </Badge>
                    </div>
                    <p className="text-[11px] text-text-muted">
                      {task.lastStatusChangedBy
                        ? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
                        : t('lastUpdatedUnknown')}
                      {task.lastStatusChangedAt
                        ? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
                        : ''}
                    </p>
                  </li>
                ))}
              </ul>
            </div>
          ))
        )}
      </div>

      {commentsSection}

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

export { CaseTaskProgressBar };
