'use client';

/**
 * 동적 게시판 등록 폼 컴포넌트
 * - mode=new 또는 /create 페이지에서 사용
 */

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { X, Save, MessageSquare } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { useMenuStore } from '@/stores/menuStore';
import { createDynamicBoardPost } from '@/components/board/DynamicBoard/actions';
import { getBoardByCode } from '@/components/board/BoardManagement/actions';

interface DynamicBoardCreateFormProps {
  boardCode: string;
}

export function DynamicBoardCreateForm({ boardCode }: DynamicBoardCreateFormProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  // 게시판 정보
  const [boardName, setBoardName] = useState<string>('게시판');

  // 폼 상태
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [isSecret, setIsSecret] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 게시판 정보 로드
  useEffect(() => {
    async function fetchBoardInfo() {
      const result = await getBoardByCode(boardCode);
      if (result.success && result.data) {
        setBoardName(result.data.boardName);
      }
    }
    fetchBoardInfo();
  }, [boardCode]);

  // 폼 제출
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!title.trim()) {
      setError('제목을 입력해주세요.');
      return;
    }

    if (!content.trim()) {
      setError('내용을 입력해주세요.');
      return;
    }

    setIsSubmitting(true);
    setError(null);

    const result = await createDynamicBoardPost(boardCode, {
      title: title.trim(),
      content: content.trim(),
      is_secret: isSecret,
    });

    if (result.success && result.data) {
      router.push(`/ko/boards/${boardCode}/${result.data.id}?mode=view`);
    } else {
      setError(result.error || '게시글 등록에 실패했습니다.');
      setIsSubmitting(false);
    }
  };

  // 취소
  const handleCancel = () => {
    router.push(`/ko/boards/${boardCode}`);
  };

  return (
    <PageLayout>
      <PageHeader
        title={boardName}
        description="새 게시글 등록"
        icon={MessageSquare}
      />

      <form onSubmit={handleSubmit} className="pb-24">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">게시글 작성</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {error && (
              <div className="p-3 bg-destructive/10 border border-destructive/20 rounded-md">
                <p className="text-sm text-destructive">{error}</p>
              </div>
            )}

            {/* 제목 */}
            <div className="space-y-2">
              <Label htmlFor="title">제목 *</Label>
              <Input
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="제목을 입력하세요"
                disabled={isSubmitting}
              />
            </div>

            {/* 내용 */}
            <div className="space-y-2">
              <Label htmlFor="content">내용 *</Label>
              <Textarea
                id="content"
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="내용을 입력하세요"
                rows={15}
                disabled={isSubmitting}
              />
            </div>

            {/* 비밀글 설정 */}
            <div className="flex items-center space-x-2">
              <Checkbox
                id="isSecret"
                checked={isSecret}
                onCheckedChange={(checked) => setIsSecret(checked as boolean)}
                disabled={isSubmitting}
              />
              <Label htmlFor="isSecret" className="font-normal cursor-pointer">
                비밀글로 등록
              </Label>
            </div>
          </CardContent>
        </Card>

      </form>

      {/* 하단 액션 버튼 (sticky) */}
      <div
        className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}
      >
        <Button type="button" variant="outline" onClick={handleCancel} disabled={isSubmitting} size="sm" className="md:size-default">
          <X className="w-4 h-4 md:mr-2" />
          <span className="hidden md:inline">취소</span>
        </Button>
        <Button onClick={(e) => { e.preventDefault(); const form = document.querySelector('form'); form?.requestSubmit(); }} disabled={isSubmitting} size="sm" className="md:size-default">
          <Save className="w-4 h-4 md:mr-2" />
          <span className="hidden md:inline">{isSubmitting ? '등록 중...' : '등록'}</span>
        </Button>
      </div>
    </PageLayout>
  );
}
