'use client';

import { useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Loader2, Paperclip, Send } from 'lucide-react';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import type { LinkedOrganizationOption, PastTreatment, PastTreatmentCase } from '@/types/treatment';
import { CaseSentLabel } from '@/components/ui/treatment/CaseSentLabel';
import { TreatmentLatestAttachmentPreview } from '@/components/ui/treatment/TreatmentLatestAttachmentPreview';

export type TreatmentPreviewMode = 'readonly' | 'editable';

interface TreatmentPreviewDialogProps {
  open: boolean;
  onClose: () => void;
  treatment: PastTreatment | null;
  mode: TreatmentPreviewMode;
  orgs?: LinkedOrganizationOption[];
  sendBusyCaseId?: string | null;
  uploadBusyCaseId?: string | null;
  onAttach?: (caseKey: string, files: FileList) => void | Promise<void>;
  onSend?: (caseKey: string, organizationIds: string[]) => void | Promise<void>;
  getCaseOrgIds?: (caseKey: string) => string[];
  onToggleCaseOrg?: (caseKey: string, organizationId: string, checked: boolean) => void;
}

function caseKey(c: PastTreatmentCase): string {
  return c.clientId ?? c.id;
}

const caseActionIconClass =
  'inline-flex items-center justify-center rounded-[var(--radius-sm)] p-1.5 text-text-secondary transition-colors hover:bg-background-card/80 hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40';

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

export function TreatmentPreviewDialog({
  open,
  onClose,
  treatment,
  mode,
  orgs = [],
  sendBusyCaseId,
  uploadBusyCaseId,
  onAttach,
  onSend,
  getCaseOrgIds,
  onToggleCaseOrg,
}: TreatmentPreviewDialogProps) {
  const t = useTranslations('treatment');
  const [expandedSendCaseId, setExpandedSendCaseId] = useState<string | null>(null);
  const fileInputsRef = useRef<Record<string, HTMLInputElement | null>>({});

  if (!open || !treatment) return null;

  const editable = mode === 'editable';
  const activeOrgs = orgs.filter((o) => o.active);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <div
        className="w-full max-w-[min(56rem,calc(100vw-15rem))] max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
        role="dialog"
        aria-modal="true"
        aria-labelledby="treatment-preview-title"
      >
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <h2 id="treatment-preview-title" className="text-lg font-semibold text-text-primary pr-2">
              {t('previewDialogTitle')}
            </h2>
            <p className="text-xs text-text-muted mt-0.5">
              {t('previewDialogSubtitle')}
            </p>
          </div>
          <DialogCloseButton onClick={onClose} />
        </div>

        <div className="border border-border/70 rounded-[var(--radius-md)] p-4 bg-background-secondary/40 space-y-3">
          <div className="flex items-start justify-between gap-2">
            <p className="text-sm font-medium text-text-primary">{treatment.title}</p>
            <span className="text-xs text-text-muted tabular-nums shrink-0">
              {new Date(treatment.treatmentAt).toLocaleDateString()}
            </span>
          </div>
          <p className="text-xs text-text-secondary capitalize">
            {t('statusLabel')} {treatment.status}
          </p>

          {treatment.cases.length === 0 ? (
            <p className="text-sm text-text-muted">{t('noCases')}</p>
          ) : (
            <div className="space-y-2">
              {treatment.cases.map((c, idx) => {
                const key = caseKey(c);
                const attachments = c.attachmentMetas ?? [];
                const latestAttachment =
                  attachments.length > 0 ? attachments[attachments.length - 1] : null;
                const sent = Boolean(c.sentAt);
                const actionsEnabled = editable && !sent;
                const selectedOrgIds = getCaseOrgIds?.(key) ?? c.sendToOrganizationIds ?? [];
                const sendExpanded = expandedSendCaseId === key;
                const comment = c.notes?.trim() ?? '';
                const attachBusy = uploadBusyCaseId === key;
                const sendBusy = sendBusyCaseId === key;
                const typeKey = TREATMENT_TYPE_KEYS[c.treatmentType as keyof typeof TREATMENT_TYPE_KEYS];
                const typeLabel = typeKey ? t(typeKey) : c.treatmentType;

                return (
                  <div
                    key={key}
                    className="rounded-[var(--radius-md)] border border-border/60 px-3 py-2 bg-background-secondary/30"
                  >
                    <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-x-4 gap-y-1">
                      <div className="min-w-0 space-y-0.5">
                        <div className="flex items-center gap-2">
                          <p className="text-xs font-medium text-text-primary">
                            {t('caseLabel', { n: idx + 1 })}
                          </p>
                          {actionsEnabled && (
                            <div className="flex items-center gap-0.5">
                              <input
                                ref={(el) => {
                                  fileInputsRef.current[key] = el;
                                }}
                                type="file"
                                multiple
                                className="sr-only"
                                aria-hidden
                                onChange={(e) => {
                                  if (e.target.files?.length) {
                                    void onAttach?.(key, e.target.files);
                                  }
                                  e.target.value = '';
                                }}
                              />
                              <button
                                type="button"
                                className={caseActionIconClass}
                                disabled={attachBusy}
                                aria-label={t('attachFilesShort')}
                                title={t('attachFilesShort')}
                                onClick={() => fileInputsRef.current[key]?.click()}
                              >
                                {attachBusy ? (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
                                ) : (
                                  <Paperclip className="h-3.5 w-3.5" aria-hidden />
                                )}
                              </button>
                              <button
                                type="button"
                                className={`${caseActionIconClass} ${
                                  sendExpanded ? 'bg-primary-soft text-primary' : ''
                                }`}
                                disabled={sendBusy}
                                aria-label={t('sendCase')}
                                title={t('sendCase')}
                                aria-expanded={sendExpanded}
                                onClick={() =>
                                  setExpandedSendCaseId((prev) => (prev === key ? null : key))
                                }
                              >
                                {sendBusy ? (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
                                ) : (
                                  <Send className="h-3.5 w-3.5" aria-hidden />
                                )}
                              </button>
                            </div>
                          )}
                        </div>
                        <p className="text-[11px] text-text-secondary capitalize">
                          {t('typeLabel')} {typeLabel}
                        </p>
                        <p className="text-[11px] text-text-secondary">
                          {t('teethLabel')}{' '}
                          {c.teeth.length ? [...c.teeth].sort().join(', ') : t('teethNone')}
                        </p>
                        {comment ? (
                          <p className="text-[11px] text-text-muted line-clamp-2" title={comment}>
                            {t('commentsLabel')} {comment}
                          </p>
                        ) : (
                          <p className="text-[11px] text-text-muted">{t('commentsEmpty')}</p>
                        )}
                      </div>

                      <div className="flex min-w-[6rem] flex-col items-end gap-1">
                        {sent && (
                          <CaseSentLabel
                            treatmentCase={c}
                            orgs={orgs}
                            className="text-[10px] text-text-muted text-right"
                          />
                        )}
                        <p className="text-[10px] uppercase tracking-wide text-text-muted">
                          {t('attachments')}
                        </p>
                        <TreatmentLatestAttachmentPreview attachment={latestAttachment} />
                      </div>
                    </div>

                    {sendExpanded && editable && !sent && (
                      <div className="mt-2 space-y-2 border-t border-border/40 pt-2">
                        <p className="text-xs font-medium text-text-secondary">
                          {t('sendToLinkedOrgs')}
                        </p>
                        {activeOrgs.length === 0 ? (
                          <p className="text-xs text-text-muted">{t('noActiveOrgs')}</p>
                        ) : (
                          <div className="flex flex-col gap-1.5">
                            {activeOrgs.map((o) => (
                              <Checkbox
                                key={o.id}
                                checked={selectedOrgIds.includes(o.id)}
                                onChange={(checked) => onToggleCaseOrg?.(key, o.id, checked)}
                                label={o.name}
                              />
                            ))}
                          </div>
                        )}
                        <Button
                          type="button"
                          variant="primary"
                          size="sm"
                          disabled={!selectedOrgIds.length || sendBusy}
                          isLoading={sendBusy}
                          onClick={() => void onSend?.(key, selectedOrgIds)}
                        >
                          {t('confirmSend')}
                        </Button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
