import { useState } from 'react';
import { motion } from 'motion/react';
import {
  VideoFilled,
  FileTextFilled,
  ShareFilled,
} from '@/shared/icons/FilledIcons';
import type { ComponentType } from 'react';
import { Button } from '@/shared/ui/button';
import {
  CHANNELS,
  TOP_CONTENT,
  OVERVIEW_STATS,
  FUNNEL_STEPS,
  CHANNEL_TREND,
  TREND_CHANNELS,
  DAYS,
  TIME_SLOTS,
  HEATMAP_DATA,
  AI_RECOMMENDATIONS,
} from '../data/performanceMocks';
import { PageContainer } from '@/shared/ui/page-container';

// ─── Component ───

const typeIcons: Record<string, ComponentType<{ size?: number; className?: string }>> = {
  video: VideoFilled,
  blog: FileTextFilled,
  social: ShareFilled,
};

const typeColors: Record<string, { bg: string; text: string }> = {
  video: { bg: 'bg-brand-tint-purple', text: 'text-brand-purple-muted' },
  blog: { bg: 'bg-brand-tint-violet', text: 'text-brand-purple-faint' },
  social: { bg: 'bg-brand-earth-bg', text: 'text-brand-earth' },
};

function heatmapColor(value: number): string {
  if (value >= 9) return 'bg-[#2d2640] text-white';
  if (value >= 7) return 'bg-[#4a4460] text-white';
  if (value >= 5) return 'bg-[#8e89a8] text-white';
  if (value >= 3) return 'bg-[#c8c4d8] text-[#4a4460]';
  return 'bg-[#f0eef5] text-[#8e89a8]';
}

export default function PerformancePage() {
  const [period, setPeriod] = useState<'7d' | '30d' | '90d'>('30d');

  const funnelMax = FUNNEL_STEPS[0].value;
  const trendMax = Math.max(...CHANNEL_TREND.flatMap(w => [w.youtube, w.instagram, w.naver, w.facebook]));

  return (
    <div className="pt-20 min-h-screen">
      {/* Header */}
      <div className="bg-brand-navy py-14 px-6 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-[500px] h-[500px] rounded-full bg-brand-purple-vivid/10 blur-[120px]" />
        <div className="absolute bottom-0 left-0 w-[300px] h-[300px] rounded-full bg-purple-500/5 blur-[100px]" />
        <PageContainer className="relative max-w-6xl px-0">
          <p className="text-xs font-semibold text-purple-300 tracking-widest uppercase mb-3">Performance Intelligence</p>
          <h1 className="font-serif text-3xl md:text-4xl font-bold text-white mb-3">성과 대시보드</h1>
          <p className="text-purple-200/70 max-w-xl mb-8">모든 채널의 마케팅 성과를 실시간으로 모니터링합니다.</p>
          <div className="flex gap-2">
            {([
              { key: '7d' as const, label: '7일' },
              { key: '30d' as const, label: '30일' },
              { key: '90d' as const, label: '90일' },
            ]).map(p => (
              <Button
                key={p.key}
                variant="ghost"
                onClick={() => setPeriod(p.key)}
                className={`px-4 py-2 h-auto rounded-full text-sm font-medium transition-all ${
                  period === p.key
                    ? 'bg-white text-brand-navy hover:bg-white hover:text-brand-navy'
                    : 'bg-white/10 text-purple-200 hover:bg-white/20 hover:text-purple-200'
                }`}
              >
                {p.label}
              </Button>
            ))}
          </div>
        </PageContainer>
      </div>

      <PageContainer className="max-w-6xl py-10">

        {/* Overview Stats */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-10">
          {OVERVIEW_STATS.map((stat, i) => (
            <motion.div
              key={stat.label}
              className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] p-4"
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: i * 0.05 }}
            >
              <p className="text-xs text-slate-500 mb-1">{stat.label}</p>
              <p className="text-xl font-bold text-brand-navy">{stat.value}</p>
              <p className={`text-xs font-medium mt-1 ${stat.positive ? 'text-brand-purple-muted' : 'text-brand-rose'}`}>{stat.delta}</p>
            </motion.div>
          ))}
        </div>

        {/* ═══ Section 1: Marketing Funnel ═══ */}
        <div className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] p-6 mb-10">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-serif font-bold text-xl text-brand-navy">마케팅 퍼널</h3>
              <p className="text-xs text-slate-500 mt-1">노출부터 전환까지 — 어디서 이탈하는지 파악</p>
            </div>
          </div>

          <div className="space-y-3">
            {FUNNEL_STEPS.map((step, i) => {
              const widthPct = Math.max((step.value / funnelMax) * 100, 8);
              const convRate = i > 0
                ? ((step.value / FUNNEL_STEPS[i - 1].value) * 100).toFixed(1)
                : null;

              return (
                <motion.div
                  key={step.label}
                  className="flex items-center gap-4"
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.4, delay: i * 0.1 }}
                >
                  {/* Label */}
                  <div className="w-24 shrink-0 text-right">
                    <p className="text-sm font-medium text-brand-navy">{step.label}</p>
                    <p className="text-xs text-slate-400">{step.labelEn}</p>
                  </div>

                  {/* Bar */}
                  <div className="flex-1 relative">
                    <motion.div
                      className="h-10 rounded-xl flex items-center px-4"
                      style={{ backgroundColor: step.color }}
                      initial={{ width: 0 }}
                      animate={{ width: `${widthPct}%` }}
                      transition={{ duration: 0.7, delay: i * 0.12 }}
                    >
                      <span className="text-sm font-bold text-white whitespace-nowrap">{step.display}</span>
                    </motion.div>
                  </div>

                  {/* Conversion Rate */}
                  <div className="w-16 shrink-0 text-right">
                    {convRate ? (
                      <span className={`text-xs font-semibold px-2 py-1 rounded-full ${
                        parseFloat(convRate) >= 10
                          ? 'bg-brand-tint-purple text-brand-purple-muted'
                          : 'bg-brand-earth-bg text-brand-earth'
                      }`}>
                        {convRate}%
                      </span>
                    ) : (
                      <span className="text-xs text-slate-300">—</span>
                    )}
                  </div>
                </motion.div>
              );
            })}
          </div>

          {/* Funnel insight */}
          <div className="mt-6 p-4 rounded-xl bg-brand-earth-bg border border-brand-earth-soft">
            <p className="text-sm text-brand-earth">
              <span className="font-semibold">병목 구간:</span> 클릭 → 웹사이트 유입 전환율 <span className="font-bold">13.9%</span> — 랜딩 페이지 최적화가 필요합니다. 업계 평균 20% 대비 낮음.
            </p>
          </div>
        </div>

        {/* ═══ Section 2: Channel Trend (Stacked Bar) ═══ */}
        <div className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] p-6 mb-10">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-serif font-bold text-xl text-brand-navy">채널별 주간 트렌드</h3>
              <p className="text-xs text-slate-500 mt-1">채널별 조회수 추이 비교 (단위: K)</p>
            </div>
            {/* Legend */}
            <div className="flex gap-3">
              {TREND_CHANNELS.map(ch => (
                <div key={ch.key} className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full" style={{ backgroundColor: ch.color }} />
                  <span className="text-xs text-slate-500">{ch.label}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="flex items-end justify-center gap-10 h-[220px] px-8">
            {CHANNEL_TREND.map((week, wi) => {
              const total = week.youtube + week.instagram + week.naver + week.facebook;
              return (
                <div key={week.week} className="flex flex-col items-center gap-2" style={{ width: '80px' }}>
                  {/* Total label above bar */}
                  <p className="text-xs text-slate-500 font-medium">{total}K</p>
                  {/* Stacked bar */}
                  <div className="w-full flex flex-col-reverse items-stretch rounded-xl overflow-hidden" style={{ height: `${(total / (trendMax * 1.5)) * 160}px` }}>
                    {TREND_CHANNELS.map(ch => {
                      const val = week[ch.key];
                      const segH = (val / total) * 100;
                      return (
                        <motion.div
                          key={ch.key}
                          className="w-full relative group"
                          style={{ height: `${segH}%`, backgroundColor: ch.color }}
                          initial={{ scaleY: 0 }}
                          animate={{ scaleY: 1 }}
                          transition={{ duration: 0.5, delay: wi * 0.1 }}
                        >
                          <div className="absolute -top-8 left-1/2 -translate-x-1/2 hidden group-hover:block bg-brand-navy text-white text-xs px-2 py-1 rounded whitespace-nowrap z-10">
                            {ch.label}: {val}K
                          </div>
                        </motion.div>
                      );
                    })}
                  </div>
                  {/* Week label */}
                  <p className="text-xs font-medium text-slate-600">{week.week}</p>
                </div>
              );
            })}
          </div>

          {/* Trend insight */}
          <div className="mt-6 p-4 rounded-xl bg-brand-tint-purple border border-brand-tint-lavender">
            <p className="text-sm text-brand-purple-muted">
              <span className="font-semibold">성장 채널:</span> Instagram 조회수 <span className="font-bold">+112%</span> (W1→W4). Naver Blog <span className="font-bold">+111%</span> 동반 성장. YouTube는 안정적 유지.
            </p>
          </div>
        </div>

        {/* ═══ Section 3: Day × Time Heatmap ═══ */}
        <div className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] p-6 mb-10">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="font-serif font-bold text-xl text-brand-navy">최적 게시 시간</h3>
              <p className="text-xs text-slate-500 mt-1">요일×시간대별 참여율 히트맵 — 진할수록 성과가 높음</p>
            </div>
            {/* Scale legend */}
            <div className="flex items-center gap-1">
              <span className="text-xs text-slate-400">낮음</span>
              {[1, 3, 5, 7, 9].map(v => (
                <div key={v} className={`w-4 h-4 rounded ${heatmapColor(v)}`} />
              ))}
              <span className="text-xs text-slate-400">높음</span>
            </div>
          </div>

          {/* Heatmap grid */}
          <div className="overflow-x-auto">
            <div className="min-w-[500px]">
              {/* Time slot headers */}
              <div className="grid grid-cols-[60px_repeat(4,1fr)] gap-2 mb-2">
                <div />
                {TIME_SLOTS.map(slot => (
                  <div key={slot} className="text-center text-xs text-slate-500 font-medium">{slot}</div>
                ))}
              </div>

              {/* Rows */}
              {DAYS.map((day, di) => (
                <motion.div
                  key={day}
                  className="grid grid-cols-[60px_repeat(4,1fr)] gap-2 mb-2"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.3, delay: di * 0.05 }}
                >
                  <div className="flex items-center justify-center text-sm font-medium text-brand-navy">{day}</div>
                  {HEATMAP_DATA[di].map((val, ti) => (
                    <div
                      key={ti}
                      className={`h-12 rounded-xl flex items-center justify-center text-sm font-semibold transition-all hover:scale-105 cursor-default ${heatmapColor(val)}`}
                    >
                      {val > 0 ? `${val * 10}%` : '-'}
                    </div>
                  ))}
                </motion.div>
              ))}
            </div>
          </div>

          {/* Heatmap insight */}
          <div className="mt-6 p-4 rounded-xl bg-brand-tint-purple border border-brand-tint-lavender">
            <p className="text-sm text-brand-purple-muted">
              <span className="font-semibold">최적 시간:</span> <span className="font-bold">금요일 저녁 (18-24시)</span> 참여율 최고. 평일 오후 (12-18시)가 전반적으로 높음. 주말 오전은 피하세요.
            </p>
          </div>
        </div>

        {/* Channel Performance Grid */}
        <h3 className="font-serif font-bold text-xl text-brand-navy mb-4">채널별 성과</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-10">
          {CHANNELS.map((ch, i) => {
            const Icon = ch.icon;
            return (
              <motion.div
                key={ch.id}
                className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] p-5"
                initial={{ opacity: 0, y: 15 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: i * 0.08 }}
              >
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: ch.bgColor }}>
                    <Icon size={20} style={{ color: ch.brandColor }} />
                  </div>
                  <div className="flex-1">
                    <h4 className="text-sm font-semibold text-brand-navy">{ch.name}</h4>
                    <p className="text-xs text-slate-400">{ch.posts}개 콘텐츠</p>
                  </div>
                  <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold ${
                    ch.score >= 70 ? 'bg-brand-tint-purple text-brand-purple-muted' :
                    ch.score >= 40 ? 'bg-brand-earth-bg text-brand-earth' :
                    ch.score > 0 ? 'bg-brand-rose-bg text-brand-rose' :
                    'bg-slate-50 text-slate-400'
                  }`}>
                    {ch.score || '-'}
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-3">
                  <MetricCell label="팔로워" value={ch.followers} delta={ch.followersDelta} />
                  <MetricCell label="조회수" value={ch.views} delta={ch.viewsDelta} />
                  <MetricCell label="참여율" value={ch.engagement} delta={ch.engagementDelta} />
                </div>
              </motion.div>
            );
          })}
        </div>

        {/* Top Content */}
        <h3 className="font-serif font-bold text-xl text-brand-navy mb-4">인기 콘텐츠 TOP 5</h3>
        <div className="bg-white rounded-2xl border border-slate-100 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] overflow-hidden mb-10">
          <div className="grid grid-cols-[1fr_100px_80px_80px_60px_70px_70px] gap-2 px-5 py-3 bg-brand-navy text-white text-xs font-medium">
            <span>콘텐츠</span>
            <span>채널</span>
            <span className="text-right">조회수</span>
            <span className="text-right">좋아요</span>
            <span className="text-right">댓글</span>
            <span className="text-right">CTR</span>
            <span className="text-right">게시일</span>
          </div>
          {TOP_CONTENT.map((content, i) => {
            const TypeIcon = typeIcons[content.type] ?? FileTextFilled;
            const colors = typeColors[content.type] ?? typeColors.blog;
            return (
              <motion.div
                key={content.id}
                className={`grid grid-cols-[1fr_100px_80px_80px_60px_70px_70px] gap-2 px-5 py-4 items-center ${
                  i % 2 === 0 ? 'bg-white' : 'bg-slate-50/50'
                } border-b border-slate-50 last:border-0`}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3, delay: i * 0.08 }}
              >
                <div className="flex items-center gap-2 min-w-0">
                  <div className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${colors.bg}`}>
                    <TypeIcon size={14} className={colors.text} />
                  </div>
                  <span className="text-sm text-brand-navy truncate">{content.title}</span>
                </div>
                <span className="text-xs text-slate-500">{content.channel}</span>
                <span className="text-sm font-medium text-brand-navy text-right">{content.views}</span>
                <span className="text-sm text-slate-600 text-right">{content.likes}</span>
                <span className="text-sm text-slate-600 text-right">{content.comments}</span>
                <span className={`text-sm font-medium text-right ${
                  parseFloat(content.ctr) >= 10 ? 'text-brand-purple-muted' : 'text-slate-600'
                }`}>{content.ctr}</span>
                <span className="text-xs text-slate-400 text-right">{content.publishedAt}</span>
              </motion.div>
            );
          })}
        </div>

        {/* AI Recommendations */}
        <div className="bg-gradient-to-r from-brand-grad-peach via-brand-grad-violet to-brand-grad-sky rounded-2xl p-8">
          <h3 className="font-serif font-bold text-xl text-brand-purple-deep mb-4">AI 개선 추천</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {AI_RECOMMENDATIONS.map((rec, i) => (
              <div key={i} className="bg-white/70 backdrop-blur-sm rounded-xl border border-white/40 p-5">
                <h4 className="font-semibold text-brand-purple-deep mb-2">{rec.title}</h4>
                <p className="text-sm text-brand-purple-deep/60">{rec.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </PageContainer>
    </div>
  );
}

function MetricCell({ label, value, delta }: { label: string; value: string; delta: string }) {
  const isPositive = delta.startsWith('+');
  const isNew = delta === 'NEW' || delta === '-';
  return (
    <div className="text-center">
      <p className="text-xs text-slate-400 mb-1">{label}</p>
      <p className="text-sm font-semibold text-brand-navy">{value}</p>
      <p className={`text-xs font-medium ${
        isNew ? 'text-slate-400' : isPositive ? 'text-brand-purple-muted' : 'text-brand-rose'
      }`}>{delta}</p>
    </div>
  );
}
