'use client';

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

import { useState, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { MessageSquare, Upload, X, File, ArrowLeft, Save } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { RichTextEditor } from '@/components/board/RichTextEditor';
import type { Inquiry, InquiryCategory, Attachment } from './types';
import { INQUIRY_CATEGORIES } from './types';

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

export function InquiryForm({ mode, initialData }: InquiryFormProps) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // ===== 폼 상태 =====
  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 handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      setAttachments((prev) => [...prev, ...Array.from(files)]);
    }
    // 파일 input 초기화
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }, []);

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

  const handleRemoveExistingFile = useCallback((id: string) => {
    setExistingAttachments((prev) => prev.filter((a) => a.id !== 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(() => {
    if (!validate()) return;

    const formData = {
      category,
      title,
      content,
      attachments,
      existingAttachments,
    };

    console.log('Submit:', mode, formData);

    // TODO: API 호출

    // 목록으로 이동
    router.push('/ko/customer-center/inquiries');
  }, [category, title, content, attachments, existingAttachments, mode, router, validate]);

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

  // 파일 크기 포맷
  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title={mode === 'create' ? '1:1 문의 등록' : '1:1 문의 수정'}
        description="1:1 문의를 등록합니다."
        icon={MessageSquare}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleCancel}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              취소
            </Button>
            <Button onClick={handleSubmit}>
              <Save className="h-4 w-4 mr-2" />
              {mode === 'create' ? '등록' : '수정'}
            </Button>
          </div>
        }
      />

      {/* 폼 카드 */}
      <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>
            <div className="flex items-center gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => fileInputRef.current?.click()}
              >
                <Upload className="h-4 w-4 mr-2" />
                찾기
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                multiple
                onChange={handleFileSelect}
                className="hidden"
              />
            </div>

            {/* 기존 파일 목록 */}
            {existingAttachments.length > 0 && (
              <div className="space-y-2 mt-3">
                {existingAttachments.map((file) => (
                  <div
                    key={file.id}
                    className="flex items-center justify-between p-2 bg-gray-50 rounded-md"
                  >
                    <div className="flex items-center gap-2">
                      <File className="h-4 w-4 text-gray-500" />
                      <span className="text-sm">{file.fileName}</span>
                      <span className="text-xs text-gray-400">
                        ({formatFileSize(file.fileSize)})
                      </span>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveExistingFile(file.id)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}

            {/* 새로 추가된 파일 목록 */}
            {attachments.length > 0 && (
              <div className="space-y-2 mt-3">
                {attachments.map((file, index) => (
                  <div
                    key={index}
                    className="flex items-center justify-between p-2 bg-blue-50 rounded-md"
                  >
                    <div className="flex items-center gap-2">
                      <File className="h-4 w-4 text-blue-500" />
                      <span className="text-sm">{file.name}</span>
                      <span className="text-xs text-gray-400">
                        ({formatFileSize(file.size)})
                      </span>
                      <span className="text-xs text-blue-500">(새 파일)</span>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveFile(index)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </PageLayout>
  );
}

export default InquiryForm;