'use client';

/**
 * 게시글 등록/수정 폼 컴포넌트
 *
 * 디자인 스펙 기준:
 * - 페이지 타이틀: 게시글 상세
 * - 페이지 설명: 게시글을 등록하고 관리합니다.
 * - 필드: 게시판, 상단 노출, 제목, 내용(에디터), 첨부파일, 작성자, 댓글, 등록일시
 */

import { useState, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { FileText, 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 { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { RichTextEditor } from '../RichTextEditor';
import type { Post, Attachment } from '../types';
import { MOCK_BOARDS } from '../types';

interface BoardFormProps {
  mode: 'create' | 'edit';
  initialData?: Post;
}

// 현재 로그인 사용자 정보 (실제로는 auth context에서 가져옴)
const CURRENT_USER = {
  id: 'user1',
  name: '홍길동',
  department: '개발팀',
  position: '과장',
};

// 상단 고정 최대 개수
const MAX_PINNED_COUNT = 5;

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

  // ===== 폼 상태 =====
  const [boardId, setBoardId] = useState(initialData?.boardId || '');
  const [isPinned, setIsPinned] = useState(initialData?.isPinned ? 'true' : 'false');
  const [title, setTitle] = useState(initialData?.title || '');
  const [content, setContent] = useState(initialData?.content || '');
  const [allowComments, setAllowComments] = useState(initialData?.allowComments ? 'true' : 'false');
  const [attachments, setAttachments] = useState<File[]>([]);
  const [existingAttachments, setExistingAttachments] = useState<Attachment[]>(
    initialData?.attachments || []
  );

  // 상단 노출 초과 Alert
  const [showPinnedAlert, setShowPinnedAlert] = useState(false);

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

  // 게시판 목록 (all 제외)
  const boardOptions = MOCK_BOARDS.filter((b) => b.id !== 'all');

  // ===== 상단 노출 변경 핸들러 =====
  const handlePinnedChange = useCallback((value: string) => {
    if (value === 'true') {
      // 상단 노출 5개 제한 체크 (Mock: 현재 3개 고정중이라고 가정)
      const currentPinnedCount = 3;
      if (currentPinnedCount >= MAX_PINNED_COUNT) {
        setShowPinnedAlert(true);
        return;
      }
    }
    setIsPinned(value);
  }, []);

  // ===== 파일 업로드 핸들러 =====
  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 (!boardId) {
      newErrors.boardId = '게시판을 선택해주세요.';
    }
    if (!title.trim()) {
      newErrors.title = '제목을 입력해주세요.';
    }
    if (!content.trim() || content === '<p></p>') {
      newErrors.content = '내용을 입력해주세요.';
    }

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

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

    const formData = {
      boardId,
      title,
      content,
      isPinned: isPinned === 'true',
      allowComments: allowComments === 'true',
      attachments,
      existingAttachments,
    };

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

    // TODO: API 호출

    // 목록으로 이동
    router.push('/ko/board');
  }, [boardId, title, content, isPinned, allowComments, 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' ? '게시글 등록' : '게시글 수정'}
        description="게시글을 등록하고 관리합니다."
        icon={FileText}
        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="board">
              게시판 <span className="text-red-500">*</span>
            </Label>
            <Select value={boardId} onValueChange={setBoardId}>
              <SelectTrigger className={errors.boardId ? 'border-red-500' : ''}>
                <SelectValue placeholder="게시판을 선택해주세요" />
              </SelectTrigger>
              <SelectContent>
                {boardOptions.map((board) => (
                  <SelectItem key={board.id} value={board.id}>
                    {board.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.boardId && (
              <p className="text-sm text-red-500">{errors.boardId}</p>
            )}
          </div>

          {/* 상단 노출 */}
          <div className="space-y-2">
            <Label>상단 노출</Label>
            <RadioGroup
              value={isPinned}
              onValueChange={handlePinnedChange}
              className="flex gap-4"
            >
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="false" id="pinned-false" />
                <Label htmlFor="pinned-false" className="font-normal cursor-pointer">
                  사용안함
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="true" id="pinned-true" />
                <Label htmlFor="pinned-true" className="font-normal cursor-pointer">
                  사용함
                </Label>
              </div>
            </RadioGroup>
          </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>

          {/* 작성자 (읽기 전용) */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>작성자</Label>
              <Input
                value={CURRENT_USER.name}
                disabled
                className="bg-gray-50"
              />
            </div>

            {/* 등록일시 (수정 모드에서만) */}
            {mode === 'edit' && initialData && (
              <div className="space-y-2">
                <Label>등록일시</Label>
                <Input
                  value={format(new Date(initialData.createdAt), 'yyyy-MM-dd HH:mm')}
                  disabled
                  className="bg-gray-50"
                />
              </div>
            )}
          </div>

          {/* 댓글 */}
          <div className="space-y-2">
            <Label>댓글</Label>
            <RadioGroup
              value={allowComments}
              onValueChange={setAllowComments}
              className="flex gap-4"
            >
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="false" id="comments-false" />
                <Label htmlFor="comments-false" className="font-normal cursor-pointer">
                  사용안함
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="true" id="comments-true" />
                <Label htmlFor="comments-true" className="font-normal cursor-pointer">
                  사용함
                </Label>
              </div>
            </RadioGroup>
          </div>

          {/* 등록일시 (등록 모드) */}
          {mode === 'create' && (
            <div className="space-y-2">
              <Label>등록일시</Label>
              <Input
                value={format(new Date(), 'yyyy-MM-dd HH:mm')}
                disabled
                className="bg-gray-50"
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 상단 노출 초과 Alert */}
      <AlertDialog open={showPinnedAlert} onOpenChange={setShowPinnedAlert}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>상단 노출 제한</AlertDialogTitle>
            <AlertDialogDescription>
              상단 노출은 5개까지 설정 가능합니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={() => setShowPinnedAlert(false)}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}

export default BoardForm;