import { useState, useCallback } from 'react';
import { motion } from 'motion/react';
import {
  VideoFilled,
  FileTextFilled,
  ShareFilled,
  MegaphoneFilled,
} from '../icons/FilledIcons';
import { SectionWrapper } from '../report/ui/SectionWrapper';
import EditEntryModal from './EditEntryModal';
import type { CalendarData, ContentCategory, CalendarEntry } from '../../types/plan';

interface ContentCalendarProps {
  data: CalendarData;
  planId?: string;
  onEntryUpdate?: (entryId: string, updates: Partial<CalendarEntry>) => void;
}

const contentTypeColors: Record<ContentCategory, { bg: string; text: string; entry: string; border: string; shadow: string }> = {
  video: { bg: 'bg-[#F3F0FF]', text: 'text-[#6C5CE7]', entry: 'bg-[#F3F0FF] border-[#D5CDF5]', border: 'border-[#D5CDF5]', shadow: 'shadow-[2px_3px_8px_rgba(155,138,212,0.15)]' },
  blog: { bg: 'bg-[#EFF0FF]', text: 'text-[#3A3F7C]', entry: 'bg-[#EFF0FF] border-[#C5CBF5]', border: 'border-[#C5CBF5]', shadow: 'shadow-[2px_3px_8px_rgba(122,132,212,0.15)]' },
  social: { bg: 'bg-[#FFF6ED]', text: 'text-[#7C5C3A]', entry: 'bg-[#FFF6ED] border-[#F5E0C5]', border: 'border-[#F5E0C5]', shadow: 'shadow-[2px_3px_8px_rgba(212,168,114,0.15)]' },
  ad: { bg: 'bg-[#FFF0F0]', text: 'text-[#7C3A4B]', entry: 'bg-[#FFF0F0] border-[#F5D5DC]', border: 'border-[#F5D5DC]', shadow: 'shadow-[2px_3px_8px_rgba(212,136,154,0.15)]' },
};

const contentTypeLabels: Record<ContentCategory, string> = {
  video: 'Video',
  blog: 'Blog',
  social: 'Social',
  ad: 'Ad',
};

const contentTypeIcons: Record<ContentCategory, typeof VideoFilled> = {
  video: VideoFilled,
  blog: FileTextFilled,
  social: ShareFilled,
  ad: MegaphoneFilled,
};

const channelEmojiMap: Record<string, string> = {
  youtube: '▶',
  instagram: '◎',
  facebook: 'f',
  blog: '✎',
  globe: '◉',
  star: '★',
  map: '◇',
  video: '▷',
};

const statusDotColors: Record<string, string> = {
  draft: 'bg-slate-300',
  approved: 'bg-purple-400',
  published: 'bg-green-400',
};

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

export default function ContentCalendar({ data, planId, onEntryUpdate }: ContentCalendarProps) {
  const [weeks, setWeeks] = useState(data.weeks);
  const [editingEntry, setEditingEntry] = useState<CalendarEntry | null>(null);
  const [filterType, setFilterType] = useState<ContentCategory | null>(null);
  const [viewMode, setViewMode] = useState<'weekly' | 'monthly'>('weekly');

  const handleEntryClick = useCallback((entry: CalendarEntry) => {
    setEditingEntry(entry);
  }, []);

  const handleSave = useCallback((updated: CalendarEntry) => {
    setWeeks((prev) =>
      prev.map((week) => ({
        ...week,
        entries: week.entries.map((e) =>
          (e.id && e.id === updated.id) ? updated : e
        ),
      }))
    );
    if (onEntryUpdate && updated.id) {
      onEntryUpdate(updated.id, updated);
    }
    setEditingEntry(null);
  }, [onEntryUpdate]);

  const handleClose = useCallback(() => {
    setEditingEntry(null);
  }, []);

  const toggleFilter = (type: ContentCategory) => {
    setFilterType((prev) => (prev === type ? null : type));
  };

  // Monthly view: flatten all weeks into one 7-day grid
  const renderMonthlyView = () => {
    const allEntries = weeks.flatMap((w) => w.entries);
    const filtered = filterType
      ? allEntries.filter((e) => e.contentType === filterType)
      : allEntries;

    const dayCells: CalendarEntry[][] = Array.from({ length: 7 }, () => []);
    for (const entry of filtered) {
      if (entry.dayOfWeek >= 0 && entry.dayOfWeek <= 6) {
        dayCells[entry.dayOfWeek].push(entry);
      }
    }

    return (
      <div className="bg-white rounded-2xl p-5 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]">
        <p className="text-sm font-bold text-[#0A1128] mb-3">월간 종합</p>
        <div className="grid grid-cols-7 gap-2">
          {dayHeaders.map((day) => (
            <div key={day} className="text-xs text-slate-400 uppercase tracking-wide text-center mb-1 font-medium">
              {day}
            </div>
          ))}
          {dayCells.map((entries, dayIdx) => (
            <div
              key={dayIdx}
              className={`min-h-[100px] rounded-xl p-1.5 ${
                entries.length > 0
                  ? 'bg-slate-50/50 border border-slate-100'
                  : 'border border-dashed border-slate-200/60'
              }`}
            >
              {entries.map((entry, entryIdx) => renderEntry(entry, entryIdx))}
            </div>
          ))}
        </div>
      </div>
    );
  };

  const renderEntry = (entry: CalendarEntry, entryIdx: number) => {
    const colors = contentTypeColors[entry.contentType];
    const Icon = contentTypeIcons[entry.contentType];
    const channelSymbol = channelEmojiMap[entry.channelIcon] || '·';
    const statusDot = statusDotColors[entry.status || 'draft'];

    return (
      <div
        key={entry.id || entryIdx}
        className={`${colors.entry} border rounded-lg p-1.5 mb-1 last:mb-0 cursor-pointer hover:ring-2 hover:ring-purple-200 transition-all group relative`}
        onClick={() => handleEntryClick(entry)}
      >
        <div className="flex items-center gap-1 mb-0.5">
          <span className={`w-1.5 h-1.5 rounded-full ${statusDot} flex-shrink-0`} />
          <span className={`text-[9px] font-bold ${colors.text} leading-none`}>
            {channelSymbol}
          </span>
          <Icon size={10} className={colors.text} />
        </div>
        <p className="text-[11px] text-slate-700 leading-tight line-clamp-2">
          {entry.title}
        </p>
        {entry.description && (
          <p className="text-[9px] text-slate-400 leading-tight mt-0.5 line-clamp-1 hidden group-hover:block">
            {entry.description}
          </p>
        )}
      </div>
    );
  };

  return (
    <SectionWrapper
      id="content-calendar"
      title="Content Calendar"
      subtitle="콘텐츠 캘린더 (월간)"
      dark
    >
      {/* Toolbar: View Toggle + Filters */}
      <div className="flex items-center justify-between mb-4 flex-wrap gap-2" data-no-print>
        {/* View toggle */}
        <div className="flex bg-slate-100 rounded-xl p-0.5">
          <button
            onClick={() => setViewMode('weekly')}
            className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
              viewMode === 'weekly'
                ? 'bg-white text-[#0A1128] shadow-sm'
                : 'text-slate-500 hover:text-slate-700'
            }`}
          >
            주간
          </button>
          <button
            onClick={() => setViewMode('monthly')}
            className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
              viewMode === 'monthly'
                ? 'bg-white text-[#0A1128] shadow-sm'
                : 'text-slate-500 hover:text-slate-700'
            }`}
          >
            월간
          </button>
        </div>

        {/* Status legend */}
        <div className="flex gap-3 text-[10px] text-slate-400">
          <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-slate-300" />초안</span>
          <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-purple-400" />승인</span>
          <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-green-400" />게시됨</span>
        </div>
      </div>

      {/* Monthly Summary */}
      <div className="flex flex-wrap gap-4 mb-8">
        {data.monthlySummary.map((item) => {
          const colors = contentTypeColors[item.type];
          const isActive = filterType === item.type;
          return (
            <motion.div
              key={item.type}
              className={`flex-1 min-w-[140px] rounded-2xl border p-4 cursor-pointer transition-all ${colors.bg} ${colors.border} ${colors.shadow} ${
                isActive ? 'ring-2 ring-purple-400 ring-offset-1' : ''
              } ${filterType && !isActive ? 'opacity-40' : ''}`}
              initial={{ opacity: 0, y: 10 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.3 }}
              onClick={() => toggleFilter(item.type)}
              data-no-print={undefined}
            >
              <div className="flex items-center gap-2 mb-2">
                <span
                  className="w-3 h-3 rounded-full"
                  style={{ backgroundColor: item.color }}
                />
                <span className={`text-sm font-medium ${colors.text}`}>{item.label}</span>
              </div>
              <span className={`text-2xl font-bold ${colors.text}`}>{item.count}</span>
            </motion.div>
          );
        })}
      </div>

      {/* Calendar Content */}
      {viewMode === 'monthly' ? (
        renderMonthlyView()
      ) : (
        /* Weekly Calendar Grid */
        weeks.map((week, weekIdx) => {
          const dayCells: CalendarEntry[][] = Array.from({ length: 7 }, () => []);
          for (const entry of week.entries) {
            if (filterType && entry.contentType !== filterType) continue;
            const dayIndex = entry.dayOfWeek;
            if (dayIndex >= 0 && dayIndex <= 6) {
              dayCells[dayIndex].push(entry);
            }
          }

          return (
            <motion.div
              key={week.weekNumber}
              className="bg-white rounded-2xl p-5 mb-4 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]"
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.4, delay: weekIdx * 0.1 }}
            >
              <p className="text-sm font-bold text-[#0A1128] mb-3">{week.label}</p>

              <div className="grid grid-cols-7 gap-2">
                {dayHeaders.map((day) => (
                  <div
                    key={day}
                    className="text-xs text-slate-400 uppercase tracking-wide text-center mb-1 font-medium"
                  >
                    {day}
                  </div>
                ))}

                {dayCells.map((entries, dayIdx) => (
                  <div
                    key={dayIdx}
                    className={`min-h-[80px] rounded-xl p-1.5 ${
                      entries.length > 0
                        ? 'bg-slate-50/50 border border-slate-100'
                        : 'border border-dashed border-slate-200/60'
                    }`}
                  >
                    {entries.map((entry, entryIdx) => renderEntry(entry, entryIdx))}
                  </div>
                ))}
              </div>
            </motion.div>
          );
        })
      )}

      {/* Color Legend (clickable filter) */}
      <div className="flex flex-wrap gap-3 mt-4">
        {(Object.keys(contentTypeColors) as ContentCategory[]).map((type) => {
          const colors = contentTypeColors[type];
          const isActive = filterType === type;
          return (
            <button
              key={type}
              onClick={() => toggleFilter(type)}
              className={`${colors.bg} ${colors.text} border ${colors.border} rounded-full px-3 py-1 text-xs font-medium ${colors.shadow} transition-all ${
                isActive ? 'ring-2 ring-purple-300' : ''
              } ${filterType && !isActive ? 'opacity-40' : ''}`}
            >
              {contentTypeLabels[type]}
            </button>
          );
        })}
        {filterType && (
          <button
            onClick={() => setFilterType(null)}
            className="text-xs text-slate-400 hover:text-slate-600 px-2 py-1 transition-colors"
          >
            필터 해제
          </button>
        )}
      </div>

      {/* Edit Modal */}
      {editingEntry && (
        <EditEntryModal
          entry={editingEntry}
          onSave={handleSave}
          onClose={handleClose}
        />
      )}
    </SectionWrapper>
  );
}
