import React, { useCallback, useEffect, useState } from 'react';
import type { VehicleRecord } from '../types';
import { DetailParamField, DetailParamSection } from './DetailParamLayout';
import { isShanghaiPlate } from '../utils/vehicle';
import {
  certPhotoStatus,
  formatLicenseBalance,
  formatLicenseDisplay,
  getLicenseCertBadgeStatus,
  LICENSE_CERT_NAV,
  LICENSE_CERT_STATUS_LEGEND,
  resolveVehicleLicenseBundle,
  type LicenseCertBadgeStatus,
  type VehicleLicenseBundle,
} from '../utils/vehicleLicenses';

interface DetailLicenseInfoTabProps {
  record: VehicleRecord;
}

interface LicensePhotoPreviewState {
  url: string;
  alt: string;
}

const LicensePhotoPreviewContext = React.createContext<((url: string, alt: string) => void) | null>(null);

function useLicensePhotoPreview() {
  return React.useContext(LicensePhotoPreviewContext);
}

function LicenseStatusDot({ status }: { status: LicenseCertBadgeStatus }) {
  return <span className={`vm-license-status-dot vm-license-status-dot--${status}`} aria-hidden="true" />;
}

function LicenseCertLegend() {
  return (
    <div className="vm-license-legend">
      <span className="vm-license-legend-label">证件状态图示</span>
      <div className="vm-license-legend-items">
        {LICENSE_CERT_STATUS_LEGEND.map((item) => (
          <span
            key={item.label}
            className={`vm-license-legend-item${item.title ? ' vm-license-legend-item--help' : ''}`}
            title={item.title}
          >
            <LicenseStatusDot status={item.status} />
            {item.label}
          </span>
        ))}
      </div>
    </div>
  );
}

function LicensePhotoPreview({
  src,
  alt,
  onClose,
}: {
  src: string;
  alt: string;
  onClose: () => void;
}) {
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKeyDown);
    return () => document.removeEventListener('keydown', onKeyDown);
  }, [onClose]);

  return (
    <div
      className="vm-license-preview"
      role="dialog"
      aria-modal="true"
      aria-label="照片预览"
      onClick={onClose}
    >
      <button
        type="button"
        className="vm-license-preview-close"
        aria-label="关闭预览"
        onClick={onClose}
      >
        ×
      </button>
      <div className="vm-license-preview-body" onClick={(event) => event.stopPropagation()}>
        <img src={src} alt={alt} />
      </div>
    </div>
  );
}

function LicensePhotoGrid({ photos, alt }: { photos: string[]; alt: string }) {
  const onPreview = useLicensePhotoPreview();
  if (!photos.length) {
    return <div className="vm-license-photos-empty">未上传</div>;
  }
  return (
    <div className="vm-license-photo-grid">
      {photos.map((url, index) => {
        const imageAlt = `${alt}${index + 1}`;
        return (
          <button
            type="button"
            className="vm-license-photo"
            key={`${url}-${index}`}
            aria-label={`预览${imageAlt}`}
            onClick={() => onPreview?.(url, imageAlt)}
          >
            <img src={url} alt={imageAlt} loading="lazy" />
          </button>
        );
      })}
    </div>
  );
}

function CertStatusBadge({ status }: { status: 'uploaded' | 'empty' }) {
  return (
    <span className={`vm-license-status vm-license-status--${status}`}>
      {status === 'uploaded' ? '已上传' : '未上传'}
    </span>
  );
}

function LicenseCertCard({
  id,
  title,
  status,
  children,
}: {
  id: string;
  title: string;
  status?: 'uploaded' | 'empty';
  children: React.ReactNode;
}) {
  return (
    <section className="vm-license-cert" id={id}>
      <div className="vm-license-cert-head">
        <h4 className="vm-license-cert-title">{title}</h4>
        {status && <CertStatusBadge status={status} />}
      </div>
      <div className="vm-license-cert-body">{children}</div>
    </section>
  );
}

function MetaFields({ items }: { items: Array<{ label: string; value: string }> }) {
  const visible = items.filter((item) => item.value && item.value !== '未上传');
  if (!visible.length) return null;
  return (
    <div className="vm-model-param-grid vm-license-meta-grid">
      {visible.map((item) => (
        <DetailParamField key={item.label} label={item.label} value={item.value} />
      ))}
    </div>
  );
}

function DriverLicenseSection({
  bundle,
  shanghaiPlate,
}: {
  bundle: VehicleLicenseBundle['driverLicense'];
  shanghaiPlate: boolean;
}) {
  return (
    <LicenseCertCard
      id="driverLicense"
      title="行驶证"
      status={certPhotoStatus(bundle)}
    >
      <LicensePhotoGrid photos={bundle.photos} alt="行驶证" />
      <div className="vm-model-param-grid">
        <DetailParamField label="注册日期" value={formatLicenseDisplay(bundle.regDate)} empty={!bundle.regDate} />
        <DetailParamField label="发证日期" value={formatLicenseDisplay(bundle.issueDate)} empty={!bundle.issueDate} />
        <DetailParamField label="强制报废日期" value={formatLicenseDisplay(bundle.scrapDate)} empty={!bundle.scrapDate} />
        <DetailParamField label="检验有效期至" value={formatLicenseDisplay(bundle.expireDate)} empty={!bundle.expireDate} />
      </div>
      {shanghaiPlate && (
        <div className="vm-license-sh-panel">
          <div className="vm-license-sh-badge">沪牌车辆等级评定</div>
          <div className="vm-model-param-grid vm-model-param-grid--1">
            <DetailParamField
              label="下次等级评定时间"
              value={formatLicenseDisplay(bundle.shNextEvaluation)}
              empty={!bundle.shNextEvaluation}
            />
          </div>
        </div>
      )}
      <MetaFields items={[
        { label: '更新方式', value: formatLicenseDisplay(bundle.updateType) },
        { label: '更新时间', value: formatLicenseDisplay(bundle.updateTime) },
        { label: '更新人', value: formatLicenseDisplay(bundle.updateUser) },
      ]}
      />
    </LicenseCertCard>
  );
}

function TransportLicenseSection({ bundle }: { bundle: VehicleLicenseBundle['transportLicense'] }) {
  return (
    <LicenseCertCard id="transportLicense" title="道路运输证" status={certPhotoStatus(bundle)}>
      <LicensePhotoGrid photos={bundle.photos} alt="道路运输证" />
      <div className="vm-model-param-grid">
        <DetailParamField label="经营许可证号" value={formatLicenseDisplay(bundle.licenseNo)} empty={!bundle.licenseNo} />
        <DetailParamField label="核发时间" value={formatLicenseDisplay(bundle.issueDate)} empty={!bundle.issueDate} />
        <DetailParamField label="证件有效期" value={formatLicenseDisplay(bundle.expireDate)} empty={!bundle.expireDate} />
        <DetailParamField label="审验有效期" value={formatLicenseDisplay(bundle.inspectValidUntil)} empty={!bundle.inspectValidUntil} />
      </div>
      <MetaFields items={[
        { label: '更新时间', value: formatLicenseDisplay(bundle.updateTime) },
        { label: '更新人', value: formatLicenseDisplay(bundle.updateUser) },
      ]}
      />
    </LicenseCertCard>
  );
}

function PhotoOnlyCertSection({
  id,
  title,
  photos,
}: {
  id: string;
  title: string;
  photos: string[];
}) {
  return (
    <LicenseCertCard id={id} title={title} status={certPhotoStatus({ photos })}>
      <LicensePhotoGrid photos={photos} alt={title} />
    </LicenseCertCard>
  );
}

function HydrogenCardSection({ bundle }: { bundle: VehicleLicenseBundle['hydrogenCard'] }) {
  const hasCard = Boolean(bundle.cardNo);
  if (!hasCard) {
    return (
      <LicenseCertCard id="hydrogenCard" title="加氢卡" status="empty">
        <div className="vm-license-h2-empty">
          <div className="vm-license-h2-empty-icon" aria-hidden="true">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
              <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
              <line x1="1" y1="10" x2="23" y2="10" />
            </svg>
          </div>
          <div className="vm-license-h2-empty-title">无加氢卡</div>
          <p className="vm-license-h2-empty-desc">该车辆尚未绑定加氢卡</p>
        </div>
      </LicenseCertCard>
    );
  }

  return (
    <LicenseCertCard id="hydrogenCard" title="加氢卡" status="uploaded">
      <div className="vm-license-h2-card">
        <div className="vm-license-h2-card-no">{bundle.cardNo}</div>
        <div className="vm-license-h2-card-balance">
          ¥ {formatLicenseBalance(bundle.balance)}
        </div>
        <div className="vm-license-h2-card-meta">
          <span>{bundle.cardType || '中石化加氢卡'}</span>
          <span>{bundle.issueUser || '—'}</span>
        </div>
      </div>
      <div className="vm-model-param-grid">
        <DetailParamField label="加氢卡号" value={bundle.cardNo} />
        <DetailParamField label="实时余额" value={`¥ ${formatLicenseBalance(bundle.balance)}`} />
        <DetailParamField label="配发时间" value={formatLicenseDisplay(bundle.issueDate)} empty={!bundle.issueDate} />
        <DetailParamField label="配发经办人" value={formatLicenseDisplay(bundle.issueUser)} empty={!bundle.issueUser} />
      </div>
    </LicenseCertCard>
  );
}

function InspectCertSection({
  id,
  title,
  bundle,
}: {
  id: string;
  title: string;
  bundle: VehicleLicenseBundle['safetyValve'];
}) {
  return (
    <LicenseCertCard id={id} title={title} status={certPhotoStatus(bundle)}>
      <LicensePhotoGrid photos={bundle.photos} alt={title} />
      <div className="vm-model-param-grid vm-model-param-grid--2">
        <DetailParamField label="本次检验日期" value={formatLicenseDisplay(bundle.inspectDate)} empty={!bundle.inspectDate} />
        <DetailParamField
          label={id === 'pressureGauge' ? '下次检验日期' : '下次检测日期'}
          value={formatLicenseDisplay(bundle.nextInspectDate)}
          empty={!bundle.nextInspectDate}
        />
      </div>
    </LicenseCertCard>
  );
}

export function DetailLicenseInfoTab({ record }: DetailLicenseInfoTabProps) {
  const [activeNav, setActiveNav] = useState<string>('driverLicense');
  const [preview, setPreview] = useState<LicensePhotoPreviewState | null>(null);
  const licenses = resolveVehicleLicenseBundle(record);
  const shanghaiPlate = isShanghaiPlate(record.plateNo);

  const openPreview = useCallback((url: string, alt: string) => {
    setPreview({ url, alt });
  }, []);

  const closePreview = useCallback(() => {
    setPreview(null);
  }, []);

  const scrollToCert = (key: string) => {
    setActiveNav(key);
    document.getElementById(key)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <LicensePhotoPreviewContext.Provider value={openPreview}>
      <div className="vm-license-tab vm-model-param-tab--readonly">
        <DetailParamSection title="证照索引">
          <LicenseCertLegend />
          <nav className="vm-license-nav" aria-label="证照分类">
            {LICENSE_CERT_NAV.map((item) => {
              const badgeStatus = getLicenseCertBadgeStatus(licenses, item.key);
              return (
                <button
                  key={item.key}
                  type="button"
                  className={`vm-license-nav-item${activeNav === item.key ? ' is-active' : ''}`}
                  onClick={() => scrollToCert(item.key)}
                >
                  <span>{item.label}</span>
                  <LicenseStatusDot status={badgeStatus} />
                </button>
              );
            })}
          </nav>
        </DetailParamSection>

        <div className="vm-license-cert-list">
          <DriverLicenseSection bundle={licenses.driverLicense} shanghaiPlate={shanghaiPlate} />
          <TransportLicenseSection bundle={licenses.transportLicense} />
          <PhotoOnlyCertSection
            id="registrationCert"
            title="登记证"
            photos={licenses.registrationCert.photos}
          />
          <PhotoOnlyCertSection
            id="specialEquipCert"
            title="特种设备使用登记证"
            photos={licenses.specialEquipCert.photos}
          />
          <LicenseCertCard id="specialEquipDecal" title="特种设备使用标识" status={certPhotoStatus(licenses.specialEquipDecal)}>
            <LicensePhotoGrid photos={licenses.specialEquipDecal.photos} alt="特种设备使用标识" />
            <div className="vm-model-param-grid vm-model-param-grid--1">
              <DetailParamField
                label="下次检验日期"
                value={formatLicenseDisplay(licenses.specialEquipDecal.nextInspectDate)}
                empty={!licenses.specialEquipDecal.nextInspectDate}
              />
            </div>
            <MetaFields items={[
              { label: '更新时间', value: formatLicenseDisplay(licenses.specialEquipDecal.updateTime) },
              { label: '更新人', value: formatLicenseDisplay(licenses.specialEquipDecal.updateUser) },
            ]}
            />
          </LicenseCertCard>
          <HydrogenCardSection bundle={licenses.hydrogenCard} />
          <InspectCertSection id="safetyValve" title="安全阀" bundle={licenses.safetyValve} />
          <InspectCertSection id="pressureGauge" title="压力表" bundle={licenses.pressureGauge} />
        </div>
        {preview && (
          <LicensePhotoPreview src={preview.url} alt={preview.alt} onClose={closePreview} />
        )}
      </div>
    </LicensePhotoPreviewContext.Provider>
  );
}
