import { useState } from 'react';
import { motion } from 'motion/react';
import { ArrowUpRight } from 'lucide-react';
import { SectionWrapper } from './ui/SectionWrapper';
import { ComparisonRow } from './ui/ComparisonRow';
import { Button } from '@/shared/ui/button';
import { PlatformIcon, resolvePlatformVariant, PLATFORM_COLORS } from '@/shared/ui/platform-icon';
import type { TransformationProposal as TransformationProposalType, PlatformStrategy } from '@/features/report/types/report';

interface TransformationProposalProps {
  data: TransformationProposalType;
}

const tabItems = [
  { key: 'brand', label: 'Brand Identity', labelKr: '브랜드 아이덴티티' },
  { key: 'content', label: 'Content Strategy', labelKr: '콘텐츠 전략' },
  { key: 'platform', label: 'Platform Strategies', labelKr: '플랫폼 전략' },
  { key: 'website', label: 'Website', labelKr: '웹사이트 개선' },
  { key: 'newChannel', label: 'New Channels', labelKr: '신규 채널' },
] as const;

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

function PlatformStrategyCard({ strategy, index }: { key?: string | number; strategy: PlatformStrategy; index: number }) {
  // strategy.icon 이 없거나 매칭 실패해도 strategy.platform 으로 fallback
  const iconVariant = strategy.icon || strategy.platform;
  const platformKey = resolvePlatformVariant(iconVariant);
  const platformColor = platformKey ? PLATFORM_COLORS[platformKey] : '#6C5CE7';

  return (
    <motion.div
      className="rounded-2xl bg-white border border-slate-100 shadow-sm p-6"
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5, delay: index * 0.1 }}
    >
      <div className="flex items-center gap-3 mb-4">
        <div
          className="w-10 h-10 rounded-xl flex items-center justify-center"
          style={{ backgroundColor: `${platformColor}14` }}
        >
          <PlatformIcon variant={iconVariant} size={20} colored />
        </div>
        <h4 className="font-bold text-brand-navy">{strategy.platform}</h4>
      </div>

      {/* Current to Target */}
      <div className="flex items-center gap-3 mb-4 text-sm">
        <span className="rounded-lg bg-brand-rose-bg px-3 py-2 text-brand-rose font-medium">
          {strategy.currentMetric}
        </span>
        <ArrowUpRight size={16} className="text-slate-400" />
        <span className="rounded-lg bg-brand-tint-purple px-3 py-2 text-brand-purple-muted font-medium">
          {strategy.targetMetric}
        </span>
      </div>

      {/* Strategy bullets */}
      <ul className="space-y-2">
        {strategy.strategies.map((s, i) => (
          <li key={i} className="flex items-start gap-2">
            <span className="shrink-0 w-2 h-2 rounded-full bg-brand-purple-vivid mt-2" />
            <div>
              <p className="text-sm font-medium text-brand-navy">{s.strategy}</p>
              <p className="text-xs text-slate-500">{s.detail}</p>
            </div>
          </li>
        ))}
      </ul>
    </motion.div>
  );
}

const priorityColor: Record<string, string> = {
  high: 'bg-brand-rose-bg text-brand-rose border-brand-rose-soft',
  medium: 'bg-brand-earth-bg text-brand-earth border-brand-earth-soft',
  low: 'bg-brand-tint-purple text-brand-purple-muted border-brand-tint-lavender',
  높음: 'bg-brand-rose-bg text-brand-rose border-brand-rose-soft',
  중간: 'bg-brand-earth-bg text-brand-earth border-brand-earth-soft',
  낮음: 'bg-brand-tint-purple text-brand-purple-muted border-brand-tint-lavender',
};

export default function TransformationProposal({ data }: TransformationProposalProps) {
  const [activeTab, setActiveTab] = useState<TabKey>('brand');

  return (
    <SectionWrapper id="transformation" title="Transformation Proposal" subtitle="As-Is → To-Be 전환 제안">
      {/* 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>

      {/* Brand Identity */}
      {activeTab === 'brand' && (
        <motion.div
          className="rounded-2xl bg-white border border-slate-100 shadow-sm p-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">브랜드 아이덴티티</h3>
          {data.brandIdentity.map((item, i) => (
            <ComparisonRow key={i} area={item.area} asIs={item.asIs} toBe={item.toBe} />
          ))}
        </motion.div>
      )}

      {/* Content Strategy */}
      {activeTab === 'content' && (
        <motion.div
          className="rounded-2xl bg-white border border-slate-100 shadow-sm p-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">콘텐츠 전략</h3>
          {data.contentStrategy.map((item, i) => (
            <ComparisonRow key={i} area={item.area} asIs={item.asIs} toBe={item.toBe} />
          ))}
        </motion.div>
      )}

      {/* Platform Strategies */}
      {activeTab === 'platform' && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {data.platformStrategies.map((strategy, i) => (
            <PlatformStrategyCard key={strategy.platform} strategy={strategy} index={i} />
          ))}
        </div>
      )}

      {/* Website Improvements */}
      {activeTab === 'website' && (
        <motion.div
          className="rounded-2xl bg-white border border-slate-100 shadow-sm p-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">웹사이트 개선</h3>
          {data.websiteImprovements.map((item, i) => (
            <ComparisonRow key={i} area={item.area} asIs={item.asIs} toBe={item.toBe} />
          ))}
        </motion.div>
      )}

      {/* New Channel Proposals */}
      {activeTab === 'newChannel' && (
        <motion.div
          className="rounded-2xl bg-white border border-slate-100 shadow-sm overflow-hidden"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-100">
                <th className="px-6 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">채널</th>
                <th className="px-6 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">우선순위</th>
                <th className="px-6 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">근거</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data.newChannelProposals.map((ch, i) => (
                <motion.tr
                  key={ch.channel}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3, delay: i * 0.05 }}
                >
                  <td className="px-6 py-4 text-sm font-medium text-brand-navy">{ch.channel}</td>
                  <td className="px-6 py-4">
                    <span
                      className={`inline-flex items-center rounded-full text-xs font-medium px-3 py-1 border ${
                        priorityColor[ch.priority.toLowerCase()] ?? 'bg-slate-50 text-slate-700 border-slate-200'
                      }`}
                    >
                      {ch.priority}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-slate-600">{ch.rationale}</td>
                </motion.tr>
              ))}
            </tbody>
          </table>
        </motion.div>
      )}
    </SectionWrapper>
  );
}
