'use client';

/**
 * 1:1 문의 등록/수정 폼 컴포넌트
 * IntegratedDetailTemplate 마이그레이션 (2025-01-20)
 *
 * 디자인 스펙:
 * - 페이지 타이틀: 1:1 문의 등록 / 1:1 문의 수정
 * - 페이지 설명: 1:1 문의를 등록합니다.
 * - 필드: 상담분류, 제목, 내용(에디터), 첨부파일
 */

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { inquiryCreateConfig, inquiryEditConfig } from './inquiryConfig';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { FileList, type NewFile, type ExistingFile } from '@/components/ui/file-list';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import dynamic from 'next/dynamic';

const RichTextEditor = dynamic(() => import('@/components/board/RichTextEditor'), { ssr: false });
import type { Inquiry, InquiryCategory, Attachment } from './types';
import { INQUIRY_CATEGORIES } from './types';
import { createPost, updatePost } from '../shared/actions';

interface InquiryFormProps {
  mode: 'create' | 'edit';
  initialData?: Inquiry;
}

export function InquiryForm({ mode, initialData }: InquiryFormProps) {
  const router = useRouter();

  // ===== 폼 상태 =====
  const [category, setCategory] = useState<InquiryCategory>(initialData?.category || 'inquiry');
  const [title, setTitle] = useState(initialData?.title || '');
  const [content, setContent] = useState(initialData?.content || '');
  const [attachments, setAttachments] = useState<File[]>([]);
  const [existingAttachments, setExistingAttachments] = useState<Attachment[]>(
    initialData?.attachments || []
  );

  // 유효성 에러
  const [errors, setErrors] = useState<Record<string, string>>({});

  // ===== 파일 업로드 핸들러 =====
  const handleFilesSelect = useCallback((files: File[]) => {
    setAttachments((prev) => [...prev, ...files]);
  }, []);

  const handleRemoveFile = useCallback((index: number) => {
    setAttachments((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const handleRemoveExistingFile = useCallback((id: string | number) => {
    setExistingAttachments((prev) => prev.filter((a) => a.id !== String(id)));
  }, []);

  // ===== 유효성 검사 =====
  const validate = useCallback(() => {
    const newErrors: Record<string, string> = {};

    if (!category) {
      newErrors.category = '상담분류를 선택해주세요.';
    }
    if (!title.trim()) {
      newErrors.title = '제목을 입력해주세요.';
    }
    if (!content.trim() || content === '<p></p>') {
      newErrors.content = '내용을 입력해주세요.';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [category, title, content]);

  // ===== 저장 핸들러 =====
  const handleSubmit = useCallback(async () => {
    if (!validate()) return;

    const postData = {
      title,
      content,
      custom_fields: {
        category,
      },
    };

    let result;
    if (mode === 'create') {
      result = await createPost('qna', postData);
    } else if (initialData) {
      result = await updatePost('qna', initialData.id, postData);
    }

    if (result?.success) {
      router.push('/ko/customer-center/qna');
    } else {
      // 에러 처리
      console.error('Submit error:', result?.error);
    }
  }, [category, title, content, mode, initialData, router, validate]);

  // ===== 취소 핸들러 =====
  const handleCancel = useCallback(() => {
    router.back();
  }, [router]);

  // ===== 폼 콘텐츠 렌더링 =====
  const renderFormContent = useCallback(() => (
    <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-1">
            문의 정보
            <span className="text-red-500">*</span>
          </CardTitle>
          <CardDescription>
            문의 내용을 입력해주세요.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 상담분류 선택 */}
          <div className="space-y-2">
            <Label htmlFor="category">
              상담분류 <span className="text-red-500">*</span>
            </Label>
            <Select value={category} onValueChange={(v) => setCategory(v as InquiryCategory)}>
              <SelectTrigger className={errors.category ? 'border-red-500' : ''}>
                <SelectValue placeholder="상담분류를 선택해주세요" />
              </SelectTrigger>
              <SelectContent>
                {INQUIRY_CATEGORIES.map((cat) => (
                  <SelectItem key={cat.value} value={cat.value}>
                    {cat.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.category && (
              <p className="text-sm text-red-500">{errors.category}</p>
            )}
          </div>

          {/* 제목 */}
          <div className="space-y-2">
            <Label htmlFor="title">
              제목 <span className="text-red-500">*</span>
            </Label>
            <Input
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="제목을 입력해주세요"
              className={errors.title ? 'border-red-500' : ''}
            />
            {errors.title && (
              <p className="text-sm text-red-500">{errors.title}</p>
            )}
          </div>

          {/* 내용 (에디터) */}
          <div className="space-y-2">
            <Label>
              내용 <span className="text-red-500">*</span>
            </Label>
            <RichTextEditor
              value={content}
              onChange={setContent}
              placeholder="내용을 입력해주세요"
              minHeight="300px"
              className={errors.content ? 'border-red-500' : ''}
            />
            {errors.content && (
              <p className="text-sm text-red-500">{errors.content}</p>
            )}
          </div>

          {/* 첨부파일 */}
          <div className="space-y-2">
            <Label>첨부파일</Label>
            <FileDropzone
              onFilesSelect={handleFilesSelect}
              multiple
              maxSize={10}
              compact
              title="클릭하거나 파일을 드래그하세요"
              description="최대 10MB"
            />
            <FileList
              files={attachments.map((file): NewFile => ({ file }))}
              existingFiles={existingAttachments.map((file): ExistingFile => ({
                id: file.id,
                name: file.fileName,
                url: file.fileUrl,
                size: file.fileSize,
              }))}
              onRemove={handleRemoveFile}
              onRemoveExisting={handleRemoveExistingFile}
              compact
            />
          </div>
        </CardContent>
      </Card>
  ), [category, title, content, errors, attachments, existingAttachments, handleFilesSelect, handleRemoveFile, handleRemoveExistingFile]);

  // Config 선택 (create/edit)
  const config = mode === 'create' ? inquiryCreateConfig : inquiryEditConfig;

  return (
    <IntegratedDetailTemplate
      config={config}
      mode={mode}
      isLoading={false}
      isSubmitting={false}
      onBack={handleCancel}
      onCancel={handleCancel}
      onSubmit={handleSubmit}
      renderForm={renderFormContent}
    />
  );
}

export default InquiryForm;