'use client';

/**
 * 팝업 등록/수정 폼 컴포넌트
 *
 * 디자인 스펙:
 * - 페이지 타이틀: 팝업 상세
 * - 필드: 대상(Select), 기간(DateRange), 제목(Input), 내용(RichTextEditor), 상태(Radio), 작성자, 등록일시
 */

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { Megaphone, ArrowLeft, Save, Loader2 } from 'lucide-react';
import { createPopup, updatePopup } from './actions';
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 { DatePicker } from '@/components/ui/date-picker';
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 { RichTextEditor } from '@/components/board/RichTextEditor';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import {
  type Popup,
  type PopupTarget,
  type PopupStatus,
  TARGET_OPTIONS,
  STATUS_OPTIONS,
} from './types';

interface PopupFormProps {
  mode: 'create' | 'edit';
  initialData?: Popup;
}

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

export function PopupForm({ mode, initialData }: PopupFormProps) {
  const router = useRouter();

  // ===== 폼 상태 =====
  const [target, setTarget] = useState<PopupTarget>(initialData?.target || 'all');
  const [title, setTitle] = useState(initialData?.title || '');
  const [content, setContent] = useState(initialData?.content || '');
  const [status, setStatus] = useState<PopupStatus>(initialData?.status || 'inactive');
  const [startDate, setStartDate] = useState(
    initialData?.startDate || format(new Date(), 'yyyy-MM-dd')
  );
  const [endDate, setEndDate] = useState(
    initialData?.endDate || format(new Date(), 'yyyy-MM-dd')
  );

  // 유효성 에러
  const [errors, setErrors] = useState<Record<string, string>>({});
  // 제출 상태
  const [isSubmitting, setIsSubmitting] = useState(false);

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

    if (!target) {
      newErrors.target = '대상을 선택해주세요.';
    }
    if (!title.trim()) {
      newErrors.title = '제목을 입력해주세요.';
    }
    if (!content.trim() || content === '<p></p>') {
      newErrors.content = '내용을 입력해주세요.';
    }
    if (!startDate) {
      newErrors.startDate = '시작일을 선택해주세요.';
    }
    if (!endDate) {
      newErrors.endDate = '종료일을 선택해주세요.';
    }
    if (startDate && endDate && startDate > endDate) {
      newErrors.endDate = '종료일은 시작일 이후여야 합니다.';
    }

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

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

    const formData = {
      target,
      title,
      content,
      status,
      startDate,
      endDate,
    };

    setIsSubmitting(true);

    try {
      const result = mode === 'create'
        ? await createPopup(formData)
        : await updatePopup(initialData!.id, formData);

      if (result.success) {
        router.push('/ko/settings/popup-management');
      } else {
        console.error('Submit failed:', result.error);
        setErrors({ submit: result.error || '저장에 실패했습니다.' });
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('Submit error:', error);
      setErrors({ submit: '서버 오류가 발생했습니다.' });
    } finally {
      setIsSubmitting(false);
    }
  }, [target, title, content, status, startDate, endDate, mode, initialData, router, validate]);

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

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title={mode === 'create' ? '팝업관리 상세' : '팝업관리 상세'}
        description="팝업 목록을 관리합니다"
        icon={Megaphone}
      />

      <div className="space-y-6">
      {/* 폼 카드 */}
      <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="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 대상 선택 */}
            <div className="space-y-2">
              <Label htmlFor="target">
                대상 <span className="text-red-500">*</span>
              </Label>
              <Select value={target} onValueChange={(v) => setTarget(v as PopupTarget)}>
                <SelectTrigger className={errors.target ? 'border-red-500' : ''}>
                  <SelectValue placeholder="대상을 선택해주세요" />
                </SelectTrigger>
                <SelectContent>
                  {TARGET_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.target && <p className="text-sm text-red-500">{errors.target}</p>}
            </div>

            {/* 기간 */}
            <div className="space-y-2">
              <Label>
                기간 <span className="text-red-500">*</span>
              </Label>
              <div className="flex items-center gap-2">
                <DatePicker
                  value={startDate}
                  onChange={(date) => setStartDate(date)}
                  className={errors.startDate ? 'border-red-500' : ''}
                />
                <span className="text-muted-foreground">~</span>
                <DatePicker
                  value={endDate}
                  onChange={(date) => setEndDate(date)}
                  className={errors.endDate ? 'border-red-500' : ''}
                />
              </div>
              {(errors.startDate || errors.endDate) && (
                <p className="text-sm text-red-500">{errors.startDate || errors.endDate}</p>
              )}
            </div>
          </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="200px"
              className={errors.content ? 'border-red-500' : ''}
            />
            {errors.content && <p className="text-sm text-red-500">{errors.content}</p>}
          </div>

          {/* 상태 + 작성자 (같은 줄) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 상태 */}
            <div className="space-y-2">
              <Label>상태</Label>
              <RadioGroup
                value={status}
                onValueChange={(v) => setStatus(v as PopupStatus)}
                className="flex gap-4"
              >
                {STATUS_OPTIONS.map((option) => (
                  <div key={option.value} className="flex items-center space-x-2">
                    <RadioGroupItem value={option.value} id={`status-${option.value}`} />
                    <Label
                      htmlFor={`status-${option.value}`}
                      className="font-normal cursor-pointer"
                    >
                      {option.label}
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            </div>

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

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

        {/* 에러 메시지 */}
        {errors.submit && (
          <div className="p-3 bg-red-50 border border-red-200 rounded-md">
            <p className="text-sm text-red-600">{errors.submit}</p>
          </div>
        )}

        {/* 버튼 영역 */}
        <div className="flex items-center justify-between">
          <Button type="button" variant="outline" onClick={handleCancel} disabled={isSubmitting}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            취소
          </Button>
          <Button type="button" onClick={handleSubmit} disabled={isSubmitting}>
            {isSubmitting ? (
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Save className="w-4 h-4 mr-2" />
            )}
            {isSubmitting ? '저장 중...' : (mode === 'create' ? '등록' : '저장')}
          </Button>
        </div>
      </div>
    </PageLayout>
  );
}

export default PopupForm;