'use client';

/**
 * 차량 관리 상세 페이지 설정
 * 레거시 5130 사이트 등록 폼 기준 (2025-01-28 스크린샷 검증)
 */

import { Car } from 'lucide-react';
import type {
  DetailConfig,
  FieldDefinition,
  SectionDefinition,
} from '@/components/templates/IntegratedDetailTemplate/types';
import type { Vehicle, VehicleFormData, OilChangeRecord, MaintenanceRecord } from '../types';
import { EditableTable, EditableColumn } from '@/components/common/EditableTable';

// ===== 엔진오일 교환 기록 테이블 컬럼 =====
const oilChangeColumns: EditableColumn<OilChangeRecord>[] = [
  {
    key: 'date',
    header: '교환일',
    type: 'text',
    placeholder: 'YYYY-MM-DD',
    width: '140px',
  },
  {
    key: 'mileage',
    header: '주행거리(km)',
    type: 'text',
    placeholder: '예: 92000',
    width: '140px',
    align: 'right',
  },
  {
    key: 'cost',
    header: '비용',
    type: 'text',
    placeholder: '예: 50,000',
    width: '120px',
    align: 'right',
  },
];

// ===== 정비내역 테이블 컬럼 =====
const maintenanceColumns: EditableColumn<MaintenanceRecord>[] = [
  {
    key: 'date',
    header: '정비일',
    type: 'text',
    placeholder: 'YYYY-MM-DD',
    width: '140px',
  },
  {
    key: 'description',
    header: '정비내역',
    type: 'text',
    placeholder: '정비 내용 입력',
  },
  {
    key: 'cost',
    header: '비용',
    type: 'text',
    placeholder: '예: 150,000',
    width: '120px',
    align: 'right',
  },
];

// ===== 새 행 생성 함수 =====
let oilRecordIdCounter = 0;
const createNewOilRecord = (): OilChangeRecord => ({
  id: `oil-${Date.now()}-${++oilRecordIdCounter}`,
  date: '',
  mileage: '',
  cost: '',
});

let maintenanceRecordIdCounter = 0;
const createNewMaintenanceRecord = (): MaintenanceRecord => ({
  id: `maint-${Date.now()}-${++maintenanceRecordIdCounter}`,
  date: '',
  description: '',
  cost: '',
});

// ===== 필드 정의 (스크린샷 순서대로) =====
export const vehicleFields: FieldDefinition[] = [
  // ===== Row 1: 차량번호, 차종, 구매유형, 최초등록/계약일 =====
  {
    key: 'vehicleNumber',
    label: '차량번호',
    type: 'text',
    required: true,
    placeholder: '차량번호 입력',
    validation: [
      { type: 'required', message: '차량번호를 입력해주세요.' },
    ],
  },
  {
    key: 'vehicleType',
    label: '차종',
    type: 'text',
    required: true,
    placeholder: '차종 입력',
    validation: [
      { type: 'required', message: '차종을 입력해주세요.' },
    ],
  },
  {
    key: 'purchaseType',
    label: '구매유형',
    type: 'select',
    placeholder: '구매유형 선택',
    options: [
      { label: '회사 소유', value: '회사 소유' },
      { label: '렌트', value: '렌트' },
      { label: '리스', value: '리스' },
    ],
  },
  {
    key: 'firstRegistrationDate',
    label: '최초등록/계약일',
    type: 'date',
    placeholder: '연도.월.일.',
  },

  // ===== Row 2: 담당자(정), 담당자(부), 구매일자, 리스/렌트 종료일 =====
  {
    key: 'managerMain',
    label: '담당자(정)',
    type: 'text',
    required: true,
    placeholder: '담당자(정) 입력',
    validation: [
      { type: 'required', message: '담당자(정)를 입력해주세요.' },
    ],
  },
  {
    key: 'managerSub',
    label: '담당자(부)',
    type: 'text',
    placeholder: '담당자(부) 입력',
  },
  {
    key: 'purchaseDate',
    label: '구매일자',
    type: 'date',
    placeholder: '연도.월.일.',
  },
  {
    key: 'leaseEndDate',
    label: '리스/렌트 종료일',
    type: 'date',
    placeholder: '연도.월.일.',
  },

  // ===== Row 3: 총 주행거리, 기록일, 검사주기 =====
  {
    key: 'totalMileage',
    label: '총 주행거리 (km)',
    type: 'text',
    placeholder: 'km',
  },
  {
    key: 'mileageRecordDate',
    label: '기록일',
    type: 'date',
    placeholder: '연도.월.일.',
  },
  {
    key: 'inspectionStartDate',
    label: '검사주기 시작',
    type: 'date',
    placeholder: '연도.월.일.',
  },
  {
    key: 'inspectionEndDate',
    label: '검사주기 종료',
    type: 'date',
    placeholder: '연도.월.일.',
  },

  // ===== 보험사 가입정보 =====
  {
    key: 'insuranceJoinDate',
    label: '가입일',
    type: 'date',
    placeholder: '연도.월.일.',
  },
  {
    key: 'insuranceCompany',
    label: '보험회사, 증서번호',
    type: 'text',
    placeholder: '보험사 및 증권번호',
  },
  {
    key: 'insuranceContact',
    label: '연락처',
    type: 'text',
    placeholder: '연락처 입력',
  },
  {
    key: 'insuranceFee',
    label: '보험료',
    type: 'text',
    placeholder: '금액',
  },
  {
    key: 'insuranceAmount',
    label: '가입금액',
    type: 'text',
    placeholder: '금액',
  },

  // ===== 엔진오일 교환 =====
  {
    key: 'oilChangeCycle',
    label: '엔진오일 교환주기(Km)',
    type: 'text',
    placeholder: 'Km',
  },
  {
    key: 'oilChangeRecords',
    label: '엔진오일 교환 기록',
    type: 'custom',
    gridSpan: 2,
    formatValue: (value: unknown) => {
      const records = (value as OilChangeRecord[]) || [];
      if (records.length === 0) return '기록 없음';
      return records.map((record, index) =>
        `${index + 1}. ${record.date} / 주행거리: ${record.mileage}km / 비용: ${record.cost}원`
      ).join('\n');
    },
    renderField: ({ value, onChange, mode }) => {
      const records = (value as OilChangeRecord[]) || [];
      const isViewMode = mode === 'view';

      // view 모드에서는 formatValue가 처리
      if (isViewMode) {
        if (records.length === 0) {
          return <div className="text-muted-foreground">기록 없음</div>;
        }
        return (
          <div className="space-y-1">
            {records.map((record, index) => (
              <div key={record.id} className="text-sm">
                {index + 1}. {record.date} / 주행거리: {record.mileage}km / 비용: {record.cost}원
              </div>
            ))}
          </div>
        );
      }

      // create/edit 모드에서는 EditableTable
      return (
        <EditableTable
          columns={oilChangeColumns}
          data={records}
          onChange={(newData) => onChange(newData)}
          createNewRow={createNewOilRecord}
          addButtonLabel="교환 기록 추가"
          emptyMessage="교환 기록이 없습니다. 기록을 추가해주세요."
          showRowNumber={true}
          compact={true}
        />
      );
    },
  },

  // ===== 정비내역 =====
  {
    key: 'maintenanceRecords',
    label: '정비 기록',
    type: 'custom',
    gridSpan: 2,
    formatValue: (value: unknown) => {
      const records = (value as MaintenanceRecord[]) || [];
      if (records.length === 0) return '기록 없음';
      return records.map((record, index) =>
        `${index + 1}. ${record.date}: ${record.description} (비용: ${record.cost}원)`
      ).join('\n');
    },
    renderField: ({ value, onChange, mode }) => {
      const records = (value as MaintenanceRecord[]) || [];
      const isViewMode = mode === 'view';

      // view 모드에서는 formatValue가 처리
      if (isViewMode) {
        if (records.length === 0) {
          return <div className="text-muted-foreground">기록 없음</div>;
        }
        return (
          <div className="space-y-1">
            {records.map((record, index) => (
              <div key={record.id} className="text-sm">
                {index + 1}. {record.date}: {record.description} (비용: {record.cost}원)
              </div>
            ))}
          </div>
        );
      }

      // create/edit 모드에서는 EditableTable
      return (
        <EditableTable
          columns={maintenanceColumns}
          data={records}
          onChange={(newData) => onChange(newData)}
          createNewRow={createNewMaintenanceRecord}
          addButtonLabel="정비 기록 추가"
          emptyMessage="정비 기록이 없습니다. 기록을 추가해주세요."
          showRowNumber={true}
          compact={true}
        />
      );
    },
  },

  // ===== 비고 =====
  {
    key: 'remarks',
    label: '비고',
    type: 'textarea',
    placeholder: '비고 입력',
    gridSpan: 2,
  },
];

// ===== 섹션 정의 (스크린샷 순서대로) =====
export const vehicleSections: SectionDefinition[] = [
  {
    id: 'basicInfo',
    title: '기본 정보',
    description: '차량의 기본 정보를 입력하세요',
    fields: ['vehicleNumber', 'vehicleType', 'purchaseType', 'firstRegistrationDate'],
  },
  {
    id: 'managerInfo',
    title: '담당자 및 구매 정보',
    description: '담당자 및 구매 관련 정보를 입력하세요',
    fields: ['managerMain', 'managerSub', 'purchaseDate', 'leaseEndDate'],
  },
  {
    id: 'mileageInfo',
    title: '주행거리 및 검사주기',
    description: '주행거리 및 검사 관련 정보를 입력하세요',
    fields: ['totalMileage', 'mileageRecordDate', 'inspectionStartDate', 'inspectionEndDate'],
  },
  {
    id: 'insuranceInfo',
    title: '보험사 가입정보',
    description: '보험 관련 정보를 입력하세요',
    fields: ['insuranceJoinDate', 'insuranceCompany', 'insuranceContact', 'insuranceFee', 'insuranceAmount'],
  },
  {
    id: 'oilChangeInfo',
    title: '엔진오일 교환',
    description: '엔진오일 교환 관련 정보를 입력하세요',
    fields: ['oilChangeCycle', 'oilChangeRecords'],
  },
  {
    id: 'maintenanceSection',
    title: '정비내역',
    description: '정비 관련 정보를 입력하세요',
    fields: ['maintenanceRecords'],
  },
  {
    id: 'remarksSection',
    title: '비고',
    description: '기타 정보를 입력하세요',
    fields: ['remarks'],
  },
];

// ===== 설정 =====
export const vehicleDetailConfig: DetailConfig<Vehicle> = {
  title: '차량',
  description: '차량 정보를 관리합니다',
  icon: Car,
  basePath: '/ko/vehicle-management/vehicle',
  fields: vehicleFields,
  sections: vehicleSections,
  gridColumns: 2,
  actions: {
    submitLabel: '저장',
    cancelLabel: '취소',
    showDelete: true,
    deleteLabel: '삭제',
    showEdit: true,
    editLabel: '수정',
    showBack: true,
    backLabel: '목록',
    deleteConfirmMessage: {
      title: '차량 삭제',
      description: '이 차량을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
    },
  },
  transformInitialData: (data: Vehicle) => ({
    vehicleNumber: data.vehicleNumber || '',
    vehicleType: data.vehicleType || '',
    purchaseType: data.purchaseType || '',
    firstRegistrationDate: data.firstRegistrationDate || '',
    managerMain: data.managerMain || '',
    managerSub: data.managerSub || '',
    purchaseDate: data.purchaseDate || '',
    leaseEndDate: data.leaseEndDate || '',
    totalMileage: data.totalMileage || '',
    mileageRecordDate: data.mileageRecordDate || '',
    inspectionStartDate: data.inspectionStartDate || '',
    inspectionEndDate: data.inspectionEndDate || '',
    insuranceJoinDate: data.insuranceJoinDate || '',
    insuranceCompany: data.insuranceCompany || '',
    insuranceContact: data.insuranceContact || '',
    insuranceFee: data.insuranceFee || '',
    insuranceAmount: data.insuranceAmount || '',
    oilChangeCycle: data.oilChangeCycle || '',
    oilChangeRecords: data.oilChangeRecords || [],
    maintenanceRecords: data.maintenanceRecords || [],
    remarks: data.remarks || '',
  }),
  transformSubmitData: (formData): Partial<VehicleFormData> => ({
    vehicleNumber: formData.vehicleNumber as string,
    vehicleType: formData.vehicleType as string,
    purchaseType: formData.purchaseType as string,
    firstRegistrationDate: formData.firstRegistrationDate as string,
    managerMain: formData.managerMain as string,
    managerSub: formData.managerSub as string,
    purchaseDate: formData.purchaseDate as string,
    leaseEndDate: formData.leaseEndDate as string,
    totalMileage: formData.totalMileage as string,
    mileageRecordDate: formData.mileageRecordDate as string,
    inspectionStartDate: formData.inspectionStartDate as string,
    inspectionEndDate: formData.inspectionEndDate as string,
    insuranceJoinDate: formData.insuranceJoinDate as string,
    insuranceCompany: formData.insuranceCompany as string,
    insuranceContact: formData.insuranceContact as string,
    insuranceFee: formData.insuranceFee as string,
    insuranceAmount: formData.insuranceAmount as string,
    oilChangeCycle: formData.oilChangeCycle as string,
    oilChangeRecords: formData.oilChangeRecords as OilChangeRecord[],
    maintenanceRecords: formData.maintenanceRecords as MaintenanceRecord[],
    remarks: formData.remarks as string,
  }),
};

// ===== 등록 페이지 Config =====
export const vehicleCreateConfig: DetailConfig = {
  title: '차량',
  description: '차량 정보를 입력하세요',
  icon: Car,
  basePath: '/vehicle-management/vehicle',
  fields: vehicleFields,
  sections: vehicleSections,
  gridColumns: 2,
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '닫기',
  },
};

// ===== 수정 페이지 Config =====
export const vehicleEditConfig: DetailConfig = {
  title: '차량',
  description: '차량 정보를 수정합니다',
  icon: Car,
  basePath: '/vehicle-management/vehicle',
  fields: vehicleFields,
  sections: vehicleSections,
  gridColumns: 2,
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '닫기',
  },
};
