import { useState } from 'react';
import { motion } from 'motion/react';
import { ArrowRight } from 'lucide-react';
import { VideoFilled } from '@/shared/icons/FilledIcons';
import { SectionWrapper } from '@/features/report/components/ui/SectionWrapper';
import { EmptyState } from '@/shared/ui/empty-state';
import { Button } from '@/shared/ui/button';
import type { ContentStrategyData } from '@/features/plan/types/plan';

interface ContentStrategyProps {
  data: ContentStrategyData;
}

const tabItems = [
  { key: 'pillars', label: 'Content Pillars', labelKr: '콘텐츠 필러' },
  { key: 'types', label: 'Content Types', labelKr: '콘텐츠 유형' },
  { key: 'workflow', label: 'Production Workflow', labelKr: '제작 워크플로우' },
  { key: 'repurposing', label: 'Repurposing', labelKr: '콘텐츠 재활용' },
] as const;

type TabKey = (typeof tabItems)[number]['key'];

const channelColorMap: Record<string, string> = {
  YouTube: 'bg-brand-rose-bg text-brand-rose',
  Instagram: 'bg-brand-rose-bg text-brand-rose',
  Blog: 'bg-brand-tint-violet text-brand-purple-faint',
  '블로그': 'bg-brand-tint-violet text-brand-purple-faint',
  '네이버블로그': 'bg-brand-tint-purple text-brand-purple-muted',
  '네이버': 'bg-brand-tint-purple text-brand-purple-muted',
  Facebook: 'bg-brand-tint-violet text-brand-purple-faint',
  '홈페이지': 'bg-slate-100 text-slate-700',
  Website: 'bg-slate-100 text-slate-700',
  TikTok: 'bg-brand-tint-purple text-brand-purple-muted',
  '카카오': 'bg-brand-earth-bg text-brand-earth',
};

function getChannelBadgeClass(channel: string): string {
  for (const [key, value] of Object.entries(channelColorMap)) {
    if (channel.toLowerCase().includes(key.toLowerCase())) return value;
  }
  return 'bg-slate-100 text-slate-700';
}

export default function ContentStrategy({ data }: ContentStrategyProps) {
  const [activeTab, setActiveTab] = useState<TabKey>('pillars');

  return (
    <SectionWrapper
      id="content-strategy"
      title="Content Strategy"
      subtitle="콘텐츠 마케팅 전략"
    >
      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-8">
        {tabItems.map((tab) => (
          <Button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            variant={activeTab === tab.key ? 'default' : 'outline'}
            className={`rounded-full px-4 py-2 h-auto text-sm font-medium ${
              activeTab === tab.key
                ? 'bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white shadow-lg hover:from-brand-purple hover:to-brand-purple-deep'
                : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {tab.label}
          </Button>
        ))}
      </div>

      {/* Tab 1: Content Pillars */}
      {activeTab === 'pillars' && (data.pillars && data.pillars.length > 0 ? (
        <motion.div
          className="grid md:grid-cols-2 gap-6"
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          {data.pillars.map((pillar, i) => (
            <motion.div
              key={pillar.title}
              className="rounded-2xl border border-slate-100 bg-white shadow-sm p-6 border-l-4"
              style={{ borderLeftColor: pillar.color }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.4, delay: i * 0.1 }}
            >
              <h4 className="font-serif text-xl font-bold text-brand-navy mb-2">
                {pillar.title}
              </h4>
              <p className="text-sm text-slate-600 mb-3">{pillar.description}</p>
              <span className="inline-block rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700 mb-4">
                {pillar.relatedUsp}
              </span>
              <ul className="space-y-2">
                {pillar.exampleTopics.map((topic, j) => (
                  <li key={j} className="flex items-start gap-2 text-sm text-slate-700">
                    <span
                      className="shrink-0 w-2 h-2 rounded-full mt-2"
                      style={{ backgroundColor: pillar.color }}
                    />
                    {topic}
                  </li>
                ))}
              </ul>
            </motion.div>
          ))}
        </motion.div>
      ) : (
        <EmptyState size="md" />
      ))}

      {/* Tab 2: Content Types */}
      {activeTab === 'types' && (data.typeMatrix && data.typeMatrix.length > 0 ? (
        <motion.div
          className="rounded-2xl overflow-hidden border border-slate-100"
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <div className="grid grid-cols-4 bg-brand-navy text-white">
            <div className="px-6 py-4 text-sm font-semibold">Format</div>
            <div className="px-6 py-4 text-sm font-semibold">Channels</div>
            <div className="px-6 py-4 text-sm font-semibold">Frequency</div>
            <div className="px-6 py-4 text-sm font-semibold">Purpose</div>
          </div>
          {data.typeMatrix.map((row, i) => (
            <motion.div
              key={row.format}
              className={`grid grid-cols-4 ${i % 2 === 0 ? 'bg-white' : 'bg-slate-50'}`}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: i * 0.04 }}
            >
              <div className="px-6 py-4 text-sm font-medium text-brand-navy">
                {row.format}
              </div>
              <div className="px-6 py-4 flex flex-wrap gap-2">
                {row.channels.map((ch) => (
                  <span
                    key={ch}
                    className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-medium ${getChannelBadgeClass(ch)}`}
                  >
                    {ch}
                  </span>
                ))}
              </div>
              <div className="px-6 py-4 text-sm text-slate-700">{row.frequency}</div>
              <div className="px-6 py-4 text-sm text-slate-600">{row.purpose}</div>
            </motion.div>
          ))}
        </motion.div>
      ) : (
        <EmptyState size="md" />
      ))}

      {/* Tab 3: Production Workflow */}
      {activeTab === 'workflow' && (() => {
        if (!data.workflow || data.workflow.length === 0) {
          return <EmptyState size="md" />;
        }
        // step 수에 따라 동일 너비 grid 컬럼 매핑 (Tailwind purge 안전)
        const cols = data.workflow.length;
        const gridColsClass =
          cols <= 3 ? 'md:grid-cols-3'
          : cols === 4 ? 'md:grid-cols-4'
          : cols === 5 ? 'md:grid-cols-5'
          : cols === 6 ? 'md:grid-cols-6'
          : cols === 7 ? 'md:grid-cols-7'
          : 'md:grid-cols-8';

        return (
          <motion.div
            className={`grid grid-cols-1 ${gridColsClass} gap-4`}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4 }}
          >
            {data.workflow.map((step, i) => (
              <div key={step.step} className="relative">
                <motion.div
                  className="h-full w-full rounded-2xl border border-slate-100 bg-white shadow-sm p-5 flex flex-col"
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.4, delay: i * 0.1 }}
                >
                  <div className="w-10 h-10 rounded-full bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white font-bold flex items-center justify-center mb-3 shrink-0">
                    {step.step}
                  </div>
                  <h4 className="font-semibold text-brand-navy mb-1">{step.name}</h4>
                  <p className="text-sm text-slate-600 mb-3 flex-1">{step.description}</p>
                  <div className="flex flex-wrap gap-2 mt-auto">
                    <span className="rounded-full bg-brand-tint-purple text-brand-purple-muted px-2 py-1 text-xs">
                      {step.owner}
                    </span>
                    <span className="rounded-full bg-slate-100 text-slate-600 px-2 py-1 text-xs">
                      {step.duration}
                    </span>
                  </div>
                </motion.div>
                {i < data.workflow.length - 1 && (
                  <ArrowRight
                    size={20}
                    className="text-slate-300 absolute -right-3 top-1/2 -translate-y-1/2 hidden md:block z-10"
                  />
                )}
              </div>
            ))}
          </motion.div>
        );
      })()}

      {/* Tab 4: Repurposing */}
      {activeTab === 'repurposing' && (
        (data.repurposingSource || (data.repurposingOutputs && data.repurposingOutputs.length > 0)) ? (
          <motion.div
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4 }}
          >
            {/* Source Card */}
            {data.repurposingSource && (
              <div className="rounded-2xl bg-gradient-to-r from-brand-purple to-brand-purple-deep p-6 text-white mb-6">
                <div className="flex items-center gap-3">
                  <VideoFilled size={28} className="text-white/60" />
                  <h4 className="font-serif text-xl font-bold">{data.repurposingSource}</h4>
                </div>
              </div>
            )}

            {/* Connector */}
            <div className="flex justify-center mb-6">
              <div className="w-px h-8 bg-gradient-to-b from-brand-purple to-slate-200" />
            </div>

            {/* Outputs Grid */}
            {data.repurposingOutputs && data.repurposingOutputs.length > 0 ? (
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-3">
                {data.repurposingOutputs.map((output, i) => (
                  <motion.div
                    key={`${output.format}-${i}`}
                    className="rounded-xl border border-slate-100 bg-white p-4"
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3, delay: i * 0.05 }}
                  >
                    <p className="font-semibold text-sm text-brand-navy mb-1">{output.format}</p>
                    <p className="text-xs text-slate-500 mb-1">{output.channel}</p>
                    <p className="text-xs text-slate-600">{output.description}</p>
                  </motion.div>
                ))}
              </div>
            ) : (
              <EmptyState size="sm" />
            )}
          </motion.div>
        ) : (
          <EmptyState size="md" />
        )
      )}
    </SectionWrapper>
  );
}
