import React, { useState } from 'react';
import { ArrowLeft, Pencil } from 'lucide-react';
import type { VehicleRecord } from '../types';
import {
  canEditOperateCity,
  displayUILabel,
  formatMileage,
  formatOperateCity,
  operateCitySourceTagClass,
  resolveOperateCitySource,
  resolveOpsManagers,
} from '../utils/vehicle';
import { DetailAccidentRecordsTab } from '../components/DetailAccidentRecordsTab';
import { DetailFaultRecordsTab } from '../components/DetailFaultRecordsTab';
import { DetailViolationRecordsTab } from '../components/DetailViolationRecordsTab';
import { DetailMovementRecordsTab } from '../components/DetailMovementRecordsTab';
import { DetailTransferRecordsTab } from '../components/DetailTransferRecordsTab';
import { DetailAnnualReviewRecordsTab } from '../components/DetailAnnualReviewRecordsTab';
import { DetailBasicInfoTab } from '../components/DetailBasicInfoTab';
import { DetailLicenseInfoTab } from '../components/DetailLicenseInfoTab';
import { DetailInsuranceRecordsTab } from '../components/DetailInsuranceRecordsTab';
import { DetailLeaseRecordsTab } from '../components/DetailLeaseRecordsTab';
import { DetailModelParamsTab } from '../components/DetailModelParamsTab';
import type { LeaseRecordRow } from '../utils/leaseRecords';
import type { FaultRecordRow } from '../utils/faultRecords';
import type { AccidentRecordRow } from '../utils/accidentRecords';
import type { ViolationRecordRow } from '../utils/violationRecords';
import type { MovementRecordRow } from '../utils/movementRecords';
import type { TransferRecordRow } from '../utils/transferRecords';
import type { AnnualReviewRecordRow } from '../utils/annualReviewRecords';

const DETAIL_TABS = [
  '基本信息',
  '型号参数',
  '证照信息',
  '保险记录',
  '租赁记录',
  '事故记录',
  '故障记录',
  '违章记录',
  '异动记录',
  '调拨记录',
  '年审记录',
] as const;

interface DetailPageProps {
  record: VehicleRecord;
  onBack: () => void;
  canEditOpsManager?: boolean;
  onEditOpsManager?: (record: VehicleRecord) => void;
  onEditOperateCity?: (record: VehicleRecord) => void;
  onOpenLicenseEdit?: (record: VehicleRecord) => void;
  onSaveField?: (recordId: string, patch: Partial<VehicleRecord>) => void;
  onOpenLeaseContract?: (record: VehicleRecord, contractNo: string) => void;
  onOpenDeliveryRecord?: (record: VehicleRecord, row: LeaseRecordRow) => void;
  onOpenReturnRecord?: (record: VehicleRecord, row: LeaseRecordRow) => void;
  onOpenInsurancePurchase?: (record: VehicleRecord, insuranceLabel: string) => void;
  onViewFaultDetail?: (record: VehicleRecord, row: FaultRecordRow) => void;
  onEditFaultRecord?: (record: VehicleRecord, row: FaultRecordRow) => void;
  onOpenAccidentDetail?: (record: VehicleRecord, row: AccidentRecordRow) => void;
  onOpenViolationDetail?: (record: VehicleRecord, row: ViolationRecordRow) => void;
  onOpenMovementDetail?: (record: VehicleRecord, row: MovementRecordRow) => void;
  onOpenTransferDetail?: (record: VehicleRecord, row: TransferRecordRow) => void;
  onOpenAnnualReviewDetail?: (record: VehicleRecord, row: AnnualReviewRecordRow) => void;
  onPreviewPolicyFile?: (fileName: string) => void;
  onDownloadPolicyFile?: (fileName: string) => void;
}

export function DetailPage({
  record,
  onBack,
  canEditOpsManager = false,
  onEditOpsManager,
  onEditOperateCity,
  onOpenLicenseEdit,
  onSaveField,
  onOpenLeaseContract,
  onOpenDeliveryRecord,
  onOpenReturnRecord,
  onOpenInsurancePurchase,
  onViewFaultDetail,
  onEditFaultRecord,
  onOpenAccidentDetail,
  onOpenViolationDetail,
  onOpenMovementDetail,
  onOpenTransferDetail,
  onOpenAnnualReviewDetail,
  onPreviewPolicyFile,
  onDownloadPolicyFile,
}: DetailPageProps) {
  const [tab, setTab] = useState<string>('基本信息');
  const online = record.onlineStatus === '在线';
  const ops = resolveOpsManagers(record);
  const citySource = resolveOperateCitySource(record);
  const cityText = formatOperateCity(record.location, '无');
  const cityEditable = canEditOperateCity(record);

  return (
    <div className="vm-detail">
      <div className="vm-detail-topbar">
        <button type="button" className="vm-btn vm-btn-back" onClick={onBack}>
          <ArrowLeft size={16} aria-hidden />
          返回列表
        </button>
      </div>

      <section className="vm-detail-card">
        <div className="vm-detail-hero">
          <div>
            <div className="vm-detail-plate">{record.plateNo}</div>
            <p className="vm-detail-meta">{displayUILabel(record.brand)} · {displayUILabel(record.model)}</p>
            <p className="vm-detail-meta mono">{record.vin}</p>
          </div>
          <div className="vm-detail-aside">
            <span className={`vm-online ${online ? 'on' : 'off'}`}>
              <span className="dot" aria-hidden />
              {record.onlineStatus || '离线'}
            </span>
            <p>{displayUILabel(record.location)}</p>
            <p className="vm-detail-gps-time">GPS {displayUILabel(record.gpsTime)}</p>
          </div>
        </div>

        <div className="vm-detail-stats">
          <div className={`vm-detail-stat${cityEditable ? ' vm-detail-stat--actionable' : ''}`}>
            <div className="vm-detail-stat-main">
              <span className="vm-detail-stat-label">运营城市</span>
              <div className="vm-detail-stat-value vm-detail-stat-value--rich">
                <div className="vm-cell-tags">
                  {cityEditable ? (
                    <button
                      type="button"
                      className="vm-link"
                      onClick={() => onEditOperateCity?.(record)}
                      title="点击修改运营城市"
                    >
                      {cityText}
                    </button>
                  ) : (
                    <span>{cityText}</span>
                  )}
                  {citySource && (
                    <span className={operateCitySourceTagClass(citySource)}>{citySource}</span>
                  )}
                </div>
              </div>
            </div>
            {cityEditable && (
              <button
                type="button"
                className="vm-detail-edit-btn vm-detail-stat-action"
                onClick={() => onEditOperateCity?.(record)}
                aria-label="修改运营城市"
                title="修改运营城市"
              >
                <Pencil size={14} aria-hidden />
              </button>
            )}
          </div>

          <div className="vm-detail-stat">
            <div className="vm-detail-stat-main">
              <span className="vm-detail-stat-label">里程数</span>
              <div className="vm-detail-stat-value vm-detail-stat-value--rich">
                <div className="vm-cell-tags">
                  <span className="vm-mileage">{formatMileage(record.mileage, online, '0 km')}</span>
                  {online && <span className="vm-tag vm-tag-teal">车机</span>}
                </div>
              </div>
            </div>
          </div>

          <div className="vm-detail-stat">
            <div className="vm-detail-stat-main">
              <span className="vm-detail-stat-label">停放区域</span>
              <span className="vm-detail-stat-value">{displayUILabel(record.parking)}</span>
            </div>
          </div>

          <div className={`vm-detail-stat${canEditOpsManager && onEditOpsManager ? ' vm-detail-stat--actionable' : ''}`}>
            <div className="vm-detail-stat-main">
              <span className="vm-detail-stat-label">运维负责人</span>
              <div className="vm-detail-stat-value">
                <span>{ops.length ? ops.join('，') : '无'}</span>
              </div>
            </div>
            {canEditOpsManager && onEditOpsManager && (
              <button
                type="button"
                className="vm-detail-edit-btn vm-detail-stat-action"
                onClick={() => onEditOpsManager(record)}
                aria-label="修改运维负责人"
                title="修改运维负责人"
              >
                <Pencil size={14} aria-hidden />
              </button>
            )}
          </div>
        </div>

        <div className="vm-tabs" role="tablist">
          {DETAIL_TABS.map((name) => (
            <button
              key={name}
              type="button"
              role="tab"
              aria-selected={tab === name}
              className={`vm-tab ${tab === name ? 'active' : ''}`}
              onClick={() => setTab(name)}
            >
              {name}
            </button>
          ))}
        </div>

        {tab === '基本信息' && (
          <DetailBasicInfoTab
            record={record}
            onOpenLicenseEdit={onOpenLicenseEdit}
            onSaveField={onSaveField}
          />
        )}

        {tab === '型号参数' && (
          <DetailModelParamsTab record={record} />
        )}

        {tab === '证照信息' && (
          <DetailLicenseInfoTab record={record} />
        )}

        {tab === '保险记录' && (
          <DetailInsuranceRecordsTab
            record={record}
            onOpenInsurancePurchase={onOpenInsurancePurchase}
            onPreviewPolicyFile={onPreviewPolicyFile}
            onDownloadPolicyFile={onDownloadPolicyFile}
          />
        )}

        {tab === '租赁记录' && (
          <DetailLeaseRecordsTab
            record={record}
            onOpenLeaseContract={onOpenLeaseContract}
            onOpenDeliveryRecord={onOpenDeliveryRecord}
            onOpenReturnRecord={onOpenReturnRecord}
          />
        )}

        {tab === '事故记录' && (
          <DetailAccidentRecordsTab
            record={record}
            onOpenAccidentDetail={onOpenAccidentDetail}
          />
        )}

        {tab === '故障记录' && (
          <DetailFaultRecordsTab
            record={record}
            onViewFaultDetail={onViewFaultDetail}
            onEditFaultRecord={onEditFaultRecord}
          />
        )}

        {tab === '违章记录' && (
          <DetailViolationRecordsTab
            record={record}
            onOpenViolationDetail={onOpenViolationDetail}
          />
        )}

        {tab === '异动记录' && (
          <DetailMovementRecordsTab
            record={record}
            onOpenMovementDetail={onOpenMovementDetail}
          />
        )}

        {tab === '调拨记录' && (
          <DetailTransferRecordsTab
            record={record}
            onOpenTransferDetail={onOpenTransferDetail}
          />
        )}

        {tab === '年审记录' && (
          <DetailAnnualReviewRecordsTab
            record={record}
            onOpenAnnualReviewDetail={onOpenAnnualReviewDetail}
          />
        )}
      </section>
    </div>
  );
}
