import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import type { CalendarEntry, ContentCategory } from '../../types/plan';

interface EditEntryModalProps {
  entry: CalendarEntry | null;
  onSave: (updated: CalendarEntry) => void;
  onClose: () => void;
  onRegenerate?: (entry: CalendarEntry) => void;
}

const CHANNELS = [
  { id: 'YouTube', icon: 'youtube' },
  { id: 'Instagram', icon: 'instagram' },
  { id: '네이버 블로그', icon: 'blog' },
  { id: 'Facebook', icon: 'facebook' },
  { id: 'TikTok', icon: 'video' },
];

const CONTENT_TYPES: { value: ContentCategory; label: string }[] = [
  { value: 'video', label: '영상' },
  { value: 'blog', label: '블로그' },
  { value: 'social', label: '소셜' },
  { value: 'ad', label: '광고' },
];

const DAYS = ['월', '화', '수', '목', '금', '토', '일'];

const STATUS_OPTIONS: { value: CalendarEntry['status']; label: string; color: string }[] = [
  { value: 'draft', label: '초안', color: 'bg-slate-200 text-slate-600' },
  { value: 'approved', label: '승인', color: 'bg-[#F3F0FF] text-[#4A3A7C]' },
  { value: 'published', label: '게시됨', color: 'bg-[#EFF0FF] text-[#3A3F7C]' },
];

export default function EditEntryModal({ entry, onSave, onClose, onRegenerate }: EditEntryModalProps) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [channel, setChannel] = useState('YouTube');
  const [channelIcon, setChannelIcon] = useState('youtube');
  const [contentType, setContentType] = useState<ContentCategory>('video');
  const [dayOfWeek, setDayOfWeek] = useState(0);
  const [status, setStatus] = useState<CalendarEntry['status']>('draft');

  useEffect(() => {
    if (!entry) return;
    setTitle(entry.title || '');
    setDescription(entry.description || '');
    setChannel(entry.channel || 'YouTube');
    setChannelIcon(entry.channelIcon || 'youtube');
    setContentType(entry.contentType || 'video');
    setDayOfWeek(entry.dayOfWeek);
    setStatus(entry.status || 'draft');
  }, [entry]);

  if (!entry) return null;

  const handleChannelChange = (channelId: string) => {
    const ch = CHANNELS.find((c) => c.id === channelId);
    if (ch) {
      setChannel(ch.id);
      setChannelIcon(ch.icon);
    }
  };

  const handleSave = () => {
    onSave({
      ...entry,
      title,
      description,
      channel,
      channelIcon,
      contentType,
      dayOfWeek,
      status,
      isManualEdit: true,
    });
  };

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        {/* Backdrop */}
        <motion.div
          className="absolute inset-0 bg-black/40 backdrop-blur-sm"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
        />

        {/* Modal */}
        <motion.div
          className="relative w-full max-w-lg bg-white rounded-2xl shadow-xl overflow-hidden"
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          transition={{ duration: 0.2 }}
        >
          {/* Header */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
            <h3 className="text-lg font-bold text-[#0A1128]">콘텐츠 편집</h3>
            <button
              onClick={onClose}
              className="text-slate-400 hover:text-slate-600 transition-colors"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Body */}
          <div className="px-6 py-5 space-y-4 max-h-[60vh] overflow-y-auto">
            {/* Title */}
            <div>
              <label className="block text-sm font-medium text-slate-600 mb-1">제목</label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#6C5CE7]/20 focus:border-[#6C5CE7] outline-none transition-all"
                placeholder="콘텐츠 제목을 입력하세요"
              />
            </div>

            {/* Description */}
            <div>
              <label className="block text-sm font-medium text-slate-600 mb-1">제작 가이드</label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                rows={3}
                className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#6C5CE7]/20 focus:border-[#6C5CE7] outline-none transition-all resize-none"
                placeholder="AI가 생성한 제작 가이드 또는 직접 메모를 입력하세요"
              />
            </div>

            {/* Channel + Content Type Row */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-slate-600 mb-1">채널</label>
                <select
                  value={channel}
                  onChange={(e) => handleChannelChange(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#6C5CE7]/20 focus:border-[#6C5CE7] outline-none bg-white"
                >
                  {CHANNELS.map((ch) => (
                    <option key={ch.id} value={ch.id}>{ch.id}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-600 mb-1">유형</label>
                <select
                  value={contentType}
                  onChange={(e) => setContentType(e.target.value as ContentCategory)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#6C5CE7]/20 focus:border-[#6C5CE7] outline-none bg-white"
                >
                  {CONTENT_TYPES.map((ct) => (
                    <option key={ct.value} value={ct.value}>{ct.label}</option>
                  ))}
                </select>
              </div>
            </div>

            {/* Day + Status Row */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-slate-600 mb-1">요일</label>
                <select
                  value={dayOfWeek}
                  onChange={(e) => setDayOfWeek(Number(e.target.value))}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#6C5CE7]/20 focus:border-[#6C5CE7] outline-none bg-white"
                >
                  {DAYS.map((d, i) => (
                    <option key={i} value={i}>{d}요일</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-600 mb-1">상태</label>
                <div className="flex gap-2">
                  {STATUS_OPTIONS.map((s) => (
                    <button
                      key={s.value}
                      onClick={() => setStatus(s.value)}
                      className={`px-3 py-2 rounded-xl text-xs font-medium transition-all ${
                        status === s.value
                          ? `${s.color} ring-2 ring-offset-1 ring-[#9B8AD4]`
                          : 'bg-slate-50 text-slate-400 hover:bg-slate-100'
                      }`}
                    >
                      {s.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div className="flex items-center justify-between px-6 py-4 border-t border-slate-100 bg-slate-50/50">
            {onRegenerate ? (
              <button
                onClick={() => onRegenerate(entry)}
                className="flex items-center gap-1.5 px-3 py-2 text-sm text-[#6C5CE7] hover:bg-[#F3F0FF] rounded-xl transition-colors"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                AI 재생성
              </button>
            ) : (
              <div />
            )}
            <div className="flex gap-2">
              <button
                onClick={onClose}
                className="px-4 py-2 text-sm text-slate-500 hover:text-slate-700 transition-colors"
              >
                취소
              </button>
              <button
                onClick={handleSave}
                className="px-5 py-2 text-sm font-medium text-white bg-[#6C5CE7] hover:bg-[#5A4BD6] rounded-xl transition-colors shadow-sm"
              >
                저장
              </button>
            </div>
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  );
}
