'use client';

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

import { FileText, Upload, X, Image as ImageIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import type {
  DetailConfig,
  FieldDefinition,
  SectionDefinition,
} from '@/components/templates/IntegratedDetailTemplate/types';
import type { VehicleLog, VehicleLogFormData } from '../types';

// ===== 차량 정보 옵션 (5130 레거시와 동일) =====
const vehicleOptions = [
  { label: '그랜드 스타렉스 - 81러8197', value: '그랜드 스타렉스 - 81러8197' },
  { label: '레이 - 224호9739', value: '레이 - 224호9739' },
  { label: '봉고III - 81러8178', value: '봉고III - 81러8178' },
  { label: '봉고III1.2톤 - 81러8178', value: '봉고III1.2톤 - 81러8178' },
  { label: '코란도스포츠 - 80소0595', value: '코란도스포츠 - 80소0595' },
  { label: '포터 - 83버5277', value: '포터 - 83버5277' },
];

// ===== 필드 정의 (5130 등록 폼 순서대로) =====
export const vehicleLogFields: FieldDefinition[] = [
  // Row 1: 작성일, 차량정보
  {
    key: 'writeDate',
    label: '작성일',
    type: 'date',
    required: true,
    validation: [
      { type: 'required', message: '작성일을 선택해주세요.' },
    ],
  },
  {
    key: 'vehicleInfo',
    label: '차량정보',
    type: 'select',
    required: true,
    placeholder: '(차량 정보 선택)',
    options: vehicleOptions,
    validation: [
      { type: 'required', message: '차량정보를 선택해주세요.' },
    ],
  },
  // Row 2: 작성자, 제목
  {
    key: 'writer',
    label: '작성자',
    type: 'text',
    required: true,
    placeholder: '작성자 입력',
    validation: [
      { type: 'required', message: '작성자를 입력해주세요.' },
    ],
  },
  {
    key: 'title',
    label: '제목',
    type: 'text',
    required: true,
    placeholder: '월별 차량사진 대지',
    validation: [
      { type: 'required', message: '제목을 입력해주세요.' },
    ],
  },
  // 사진 첨부 (custom)
  {
    key: 'images',
    label: '사진 첨부',
    type: 'custom',
    gridSpan: 2,
    formatValue: (value: unknown) => {
      const images = (value as string[]) || [];
      if (images.length === 0) return '첨부된 사진 없음';
      return `${images.length}개 사진 첨부됨`;
    },
    renderField: ({ value, onChange, mode }) => {
      const images = (value as string[]) || [];
      const isViewMode = mode === 'view';

      // view 모드
      if (isViewMode) {
        if (images.length === 0) {
          return <div className="text-muted-foreground">첨부된 사진 없음</div>;
        }
        return (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {images.map((img, index) => (
              <div key={index} className="relative aspect-square bg-gray-100 rounded-lg overflow-hidden">
                <img
                  src={img}
                  alt={`첨부 사진 ${index + 1}`}
                  className="w-full h-full object-cover"
                />
              </div>
            ))}
          </div>
        );
      }

      // create/edit 모드
      const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (!files) return;

        // 파일을 URL로 변환 (실제 구현에서는 서버 업로드 필요)
        const newImages: string[] = [...images];
        Array.from(files).forEach((file) => {
          const url = URL.createObjectURL(file);
          newImages.push(url);
        });
        onChange(newImages);
      };

      const handleRemove = (index: number) => {
        const newImages = images.filter((_, i) => i !== index);
        onChange(newImages);
      };

      return (
        <div className="space-y-4">
          {/* 업로드 영역 */}
          <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-primary/50 transition-colors">
            <div className="flex flex-col items-center justify-center pt-5 pb-6">
              <Upload className="w-8 h-8 text-gray-400 mb-2" />
              <p className="text-sm text-gray-600">클릭하여 사진 업로드</p>
              <p className="text-xs text-gray-500">PNG, JPG (최대 10MB)</p>
            </div>
            <Input
              type="file"
              accept="image/*"
              multiple
              onChange={handleFileSelect}
              className="hidden"
            />
          </label>

          {/* 업로드된 이미지 미리보기 */}
          {images.length > 0 && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {images.map((img, index) => (
                <div key={index} className="relative aspect-square bg-gray-100 rounded-lg overflow-hidden group">
                  <img
                    src={img}
                    alt={`첨부 사진 ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                  <Button
                    type="button"
                    variant="destructive"
                    size="icon"
                    className="absolute top-2 right-2 w-6 h-6 opacity-0 group-hover:opacity-100 transition-opacity"
                    onClick={() => handleRemove(index)}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}

          {images.length === 0 && (
            <p className="text-sm text-muted-foreground text-center">
              <ImageIcon className="inline w-4 h-4 mr-1" />
              아직 첨부된 사진이 없습니다
            </p>
          )}
        </div>
      );
    },
  },
];

// ===== 섹션 정의 =====
export const vehicleLogSections: SectionDefinition[] = [
  {
    id: 'basicInfo',
    title: '기본 정보',
    description: '차량일지 기본 정보를 입력하세요',
    fields: ['writeDate', 'vehicleInfo', 'writer', 'title'],
  },
  {
    id: 'imageSection',
    title: '사진 첨부',
    description: '차량 사진을 첨부하세요',
    fields: ['images'],
  },
];

// ===== 설정 =====
export const vehicleLogDetailConfig: DetailConfig<VehicleLog> = {
  title: '차량일지',
  description: '차량일지 정보를 관리합니다',
  icon: FileText,
  basePath: '/ko/vehicle-management/vehicle-log',
  fields: vehicleLogFields,
  sections: vehicleLogSections,
  gridColumns: 2,
  actions: {
    submitLabel: '저장',
    cancelLabel: '취소',
    showDelete: true,
    deleteLabel: '삭제',
    showEdit: true,
    editLabel: '수정',
    showBack: true,
    backLabel: '목록',
    deleteConfirmMessage: {
      title: '차량일지 삭제',
      description: '이 차량일지를 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
    },
  },
  transformInitialData: (data: VehicleLog) => ({
    writeDate: data.writeDate || '',
    vehicleInfo: data.vehicleInfo || '',
    writer: data.writer || '',
    title: data.title || '',
    images: data.images || [],
  }),
  transformSubmitData: (formData): Partial<VehicleLogFormData> => ({
    writeDate: formData.writeDate as string,
    vehicleInfo: formData.vehicleInfo as string,
    writer: formData.writer as string,
    title: formData.title as string,
    images: formData.images as string[],
  }),
};

export const vehicleLogCreateConfig: DetailConfig = {
  title: '차량일지',
  description: '차량일지를 등록합니다',
  icon: FileText,
  basePath: '/vehicle-management/vehicle-log',
  fields: vehicleLogFields,
  sections: vehicleLogSections,
  gridColumns: 2,
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '닫기',
  },
};

export const vehicleLogEditConfig: DetailConfig = {
  title: '차량일지',
  description: '차량일지를 수정합니다',
  icon: FileText,
  basePath: '/vehicle-management/vehicle-log',
  fields: vehicleLogFields,
  sections: vehicleLogSections,
  gridColumns: 2,
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '닫기',
  },
};
