import { useState, useRef, useEffect } from 'react';
import { motion } from 'motion/react';
import { ArrowRight } from 'lucide-react';
import {
  CheckFilled,
  CrossFilled,
  WarningFilled,
} 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 { Input } from '@/shared/ui/input';
// import { BrandAppliedPreview } from './BrandAppliedPreview';
import {
  tabItems,
  type TabKey,
  statusColor,
  statusLabel,
} from '../data/brandingGuideConstants';
import { resolveChannelIcon } from '@/shared/icons/channelIcons';
import type { BrandGuide, ColorSwatch } from '@/features/plan/types/plan';
import type { BrandInconsistency } from '@/features/report/types/report';

interface BrandingGuideProps {
  data: BrandGuide;
  clinicName: string;
}

/* ─── 색상 스와치 편집 팝오버 ─── */
function ColorSwatchCard({ swatch, onUpdate }: { swatch: ColorSwatch; onUpdate: (newHex: string) => void }) {
  const [open, setOpen] = useState(false);
  const [hexInput, setHexInput] = useState(swatch.hex);
  const popoverRef = useRef<HTMLDivElement>(null);
  const colorInputRef = useRef<HTMLInputElement>(null);

  // 외부 클릭 시 닫기
  useEffect(() => {
    if (!open) return;
    function handleClick(e: MouseEvent) {
      if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [open]);

  // 외부에서 스와치가 변경될 때 hex 입력 동기화
  useEffect(() => { setHexInput(swatch.hex); }, [swatch.hex]);

  const applyHex = (value: string) => {
    const normalized = value.startsWith('#') ? value : `#${value}`;
    if (/^#[0-9A-Fa-f]{6}$/.test(normalized)) {
      onUpdate(normalized.toUpperCase());
      setHexInput(normalized.toUpperCase());
    }
  };

  return (
    <div ref={popoverRef} className="relative rounded-2xl border border-slate-100 overflow-visible shadow-[3px_4px_12px_rgba(0,0,0,0.06)]">
      {/* Swatch — click to open */}
      <button
        type="button"
        className="w-full h-20 rounded-t-2xl cursor-pointer group relative overflow-hidden"
        style={{ backgroundColor: swatch.hex }}
        onClick={() => { setOpen((p) => !p); setHexInput(swatch.hex); }}
        title="색상 편집"
      >
        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors flex items-center justify-center">
          <svg className="w-5 h-5 text-white opacity-0 group-hover:opacity-80 transition-opacity drop-shadow" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15.232 5.232l3.536 3.536M9 11l6-6 3 3-6 6H9v-3z" />
          </svg>
        </div>
      </button>

      <div className="p-3">
        <p className="font-mono text-sm text-slate-700">{swatch.hex}</p>
        <p className="font-medium text-sm text-brand-navy">{swatch.name}</p>
        <p className="text-xs text-slate-500">{swatch.usage}</p>
      </div>

      {/* Edit Popover */}
      {open && (
        <div className="absolute top-full left-0 mt-2 z-50 bg-white rounded-2xl shadow-[4px_6px_16px_rgba(0,0,0,0.12)] border border-slate-100 p-4 w-52">
          {/* Native color wheel */}
          <div className="flex items-center gap-3 mb-3">
            <input
              ref={colorInputRef}
              type="color"
              value={swatch.hex}
              onChange={(e) => { onUpdate(e.target.value.toUpperCase()); setHexInput(e.target.value.toUpperCase()); }}
              className="w-10 h-10 rounded-xl border border-slate-200 cursor-pointer p-0.5"
            />
            <span className="text-xs text-slate-500">색상 선택</span>
          </div>

          {/* Hex input */}
          <div className="flex items-center gap-2">
            <span className="text-xs font-mono text-slate-400">#</span>
            <Input
              type="text"
              value={hexInput.replace('#', '')}
              onChange={(e) => setHexInput(`#${e.target.value}`)}
              onBlur={(e) => applyHex(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') applyHex(hexInput); }}
              maxLength={6}
              placeholder="6C5CE7"
              className="flex-1 font-mono text-sm border-slate-200 rounded-lg px-2 py-1.5 h-auto text-brand-navy focus-visible:ring-brand-purple-vivid/30 focus-visible:border-brand-purple-vivid"
            />
          </div>
          <Button
            type="button"
            onClick={() => setOpen(false)}
            className="mt-3 w-full text-xs py-1.5 h-auto rounded-xl bg-brand-tint-purple text-brand-purple-muted font-medium hover:bg-[#EBE6FF]"
          >
            완료
          </Button>
        </div>
      )}
    </div>
  );
}

/* ─── 비주얼 아이덴티티 탭 ─── */
function VisualIdentityTab({ data, clinicName }: { data: BrandGuide; clinicName: string }) {
  const [colors, setColors] = useState<ColorSwatch[]>(data.colors);

  const handleColorUpdate = (idx: number, newHex: string) => {
    setColors((prev) => prev.map((c, i) => i === idx ? { ...c, hex: newHex } : c));
  };

  return (
    <motion.div
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="space-y-8"
    >
      {/* Color Palette */}
      <div>
        <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">Color Palette</h3>
        {colors.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            {colors.map((swatch: ColorSwatch, idx: number) => (
              <ColorSwatchCard
                key={swatch.hex + idx}
                swatch={swatch}
                onUpdate={(newHex) => handleColorUpdate(idx, newHex)}
              />
            ))}
          </div>
        ) : (
          <EmptyState size="md" />
        )}
      </div>

      {/* Typography */}
      <div>
        <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">Typography</h3>
        {data.fonts.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {data.fonts.map((spec) => (
              <div
                key={`${spec.family}-${spec.weight}`}
                className="rounded-2xl border border-slate-100 p-5"
              >
                <p className="text-sm text-slate-500 uppercase tracking-wide mb-2">
                  {spec.family}
                </p>
                <p
                  className={`mb-3 text-brand-navy ${
                    spec.weight.toLowerCase().includes('bold')
                      ? 'text-2xl font-bold'
                      : 'text-lg'
                  }`}
                  style={{ fontFamily: spec.family }}
                >
                  {spec.sampleText}
                </p>
                <p className="text-xs text-slate-500">
                  <span className="font-medium text-slate-700">{spec.weight}</span> &middot;{' '}
                  {spec.usage}
                </p>
              </div>
            ))}
          </div>
        ) : (
          <EmptyState size="md" />
        )}
      </div>

      {/* Logo Rules — DO / DON'T split columns */}
      <div>
        <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">Logo Rules</h3>
        {data.logoRules.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* DO Column */}
            <div>
              <div className="flex items-center gap-2 mb-3">
                <CheckFilled size={18} className="text-brand-purple-soft" />
                <span className="font-semibold text-brand-purple-muted text-sm uppercase tracking-widest">DO</span>
              </div>
              {data.logoRules.some((r) => r.correct) ? (
                <div className="space-y-3">
                  {data.logoRules.filter((r) => r.correct).map((rule) => (
                    <div
                      key={rule.rule}
                      className="rounded-2xl p-4 border-2 border-brand-tint-lavender bg-brand-tint-purple/40"
                    >
                      <div className="flex items-start gap-3">
                        <CheckFilled size={16} className="text-brand-purple-soft shrink-0 mt-0.5" />
                        <div>
                          <p className="font-semibold text-brand-navy text-sm">{rule.rule}</p>
                          <p className="text-xs text-slate-600 mt-1">{rule.description}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <EmptyState size="sm" />
              )}
            </div>

            {/* DON'T Column */}
            <div>
              <div className="flex items-center gap-2 mb-3">
                <CrossFilled size={18} className="text-brand-rose-mid" />
                <span className="font-semibold text-brand-rose text-sm uppercase tracking-widest">DON&apos;T</span>
              </div>
              {data.logoRules.some((r) => !r.correct) ? (
                <div className="space-y-3">
                  {data.logoRules.filter((r) => !r.correct).map((rule) => (
                    <div
                      key={rule.rule}
                      className="rounded-2xl p-4 border-2 border-brand-rose-soft bg-brand-rose-bg/40"
                    >
                      <div className="flex items-start gap-3">
                        <CrossFilled size={16} className="text-brand-rose-mid shrink-0 mt-0.5" />
                        <div>
                          <p className="font-semibold text-brand-navy text-sm">{rule.rule}</p>
                          <p className="text-xs text-slate-600 mt-1">{rule.description}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <EmptyState size="sm" />
              )}
            </div>
          </div>
        ) : (
          <EmptyState size="md" />
        )}
      </div>

      {/* Brand applied preview — IG/YouTube mockup */}
      {/* {data.colors.length > 0 && data.fonts.length > 0 && (
        <BrandAppliedPreview data={data} clinicName={clinicName} />
      )} */}
    </motion.div>
  );
}

/* ─── 톤 & 보이스 탭 ─── */
function ToneVoiceTab({ tone }: { tone: BrandGuide['toneOfVoice'] }) {
  return (
    <motion.div
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="space-y-6"
    >
      {/* Personality */}
      <div>
        <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">Personality</h3>
        {tone.personality && tone.personality.length > 0 ? (
          <div className="flex flex-wrap gap-2">
            {tone.personality.map((trait) => (
              <span
                key={trait}
                className="bg-gradient-to-r from-brand-purple/10 to-brand-purple-deep/10 text-brand-purple border border-purple-200 rounded-full px-4 py-2 font-medium text-sm"
              >
                {trait}
              </span>
            ))}
          </div>
        ) : (
          <EmptyState size="sm" />
        )}
      </div>

      {/* Communication Style */}
      <div>
        <h3 className="font-serif font-bold text-2xl text-brand-navy mb-4">Communication Style</h3>
        {tone.communicationStyle ? (
          <div className="rounded-2xl bg-slate-50 p-6">
            <p className="text-base leading-relaxed text-slate-700">
              {tone.communicationStyle}
            </p>
          </div>
        ) : (
          <EmptyState size="sm" />
        )}
      </div>

      {/* DO / DON'T */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <h4 className="font-semibold text-brand-purple-muted mb-3 flex items-center gap-2">
            <CheckFilled size={16} className="text-brand-purple-soft" /> DO
          </h4>
          {tone.doExamples && tone.doExamples.length > 0 ? (
            <div className="space-y-3">
              {tone.doExamples.map((example, i) => (
                <div
                  key={i}
                  className="border-l-4 border-brand-purple-soft bg-brand-tint-purple/30 p-4 rounded-r-lg"
                >
                  <p className="text-sm text-slate-700">{example}</p>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState size="sm" />
          )}
        </div>
        <div>
          <h4 className="font-semibold text-brand-rose mb-3 flex items-center gap-2">
            <CrossFilled size={16} className="text-brand-rose-mid" /> DON&apos;T
          </h4>
          {tone.dontExamples && tone.dontExamples.length > 0 ? (
            <div className="space-y-3">
              {tone.dontExamples.map((example, i) => (
                <div
                  key={i}
                  className="border-l-4 border-brand-rose-mid bg-brand-rose-bg/30 p-4 rounded-r-lg"
                >
                  <p className="text-sm text-slate-700">{example}</p>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState size="sm" />
          )}
        </div>
      </div>
    </motion.div>
  );
}

/* ─── 채널 규칙 탭 ─── */
function ChannelRulesTab({ channels }: { channels: BrandGuide['channelBranding'] }) {
  if (!channels || channels.length === 0) {
    return (
      <motion.div animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.4 }}>
        <EmptyState size="md" />
      </motion.div>
    );
  }
  return (
    <motion.div
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
    >
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {channels.map((ch) => {
          const Icon = resolveChannelIcon(ch.channel, ch.icon);
          return (
            <div key={ch.channel} className="rounded-2xl border border-slate-100 p-5">
              {/* Header */}
              <div className="flex items-center gap-3 mb-4">
                <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-brand-purple-vivid/10 to-brand-purple/10 flex items-center justify-center">
                  <Icon size={18} className="text-brand-purple-vivid" />
                </div>
                <p className="font-bold text-brand-navy">{ch.channel}</p>
                <span
                  className={`ml-auto text-xs font-medium px-3 py-1 rounded-full border ${
                    statusColor[ch.currentStatus]
                  }`}
                >
                  {statusLabel[ch.currentStatus]}
                </span>
              </div>

              {/* Specs */}
              <div className="space-y-3 text-sm">
                <div>
                  <p className="text-slate-500 text-xs uppercase tracking-wide mb-1">Profile Photo</p>
                  <p className="text-slate-700 font-medium">{ch.profilePhoto}</p>
                </div>
                <div>
                  <p className="text-slate-500 text-xs uppercase tracking-wide mb-1">Banner Spec</p>
                  <p className="text-slate-700 font-medium">{ch.bannerSpec}</p>
                </div>
                <div>
                  <p className="text-slate-500 text-xs uppercase tracking-wide mb-1">Bio Template</p>
                  <div className="bg-slate-50 rounded-xl p-3">
                    <p className="font-mono text-xs text-slate-600 whitespace-pre-wrap">
                      {ch.bioTemplate}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </motion.div>
  );
}

/* ─── 브랜드 일관성 탭 (아코디언) ─── */
function BrandConsistencyTab({ inconsistencies }: { inconsistencies: BrandInconsistency[] }) {
  const [expanded, setExpanded] = useState<number | null>(0);

  if (!inconsistencies || inconsistencies.length === 0) {
    return (
      <motion.div animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.4 }}>
        <EmptyState size="md" />
      </motion.div>
    );
  }

  return (
    <motion.div
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
    >
      <div className="space-y-3">
        {inconsistencies.map((item, i) => (
          <div
            key={item.field}
            className="rounded-2xl border border-slate-100 bg-white shadow-sm overflow-hidden"
          >
            {/* Header */}
            <Button
              type="button"
              variant="ghost"
              onClick={() => setExpanded(expanded === i ? null : i)}
              className="w-full flex items-center justify-between p-5 h-auto text-left hover:bg-slate-50/50 rounded-none"
            >
              {(() => {
                const mismatchCount = item.values.filter((v) => !v.isCorrect).length;
                const isAllConsistent = mismatchCount === 0;
                return (
                  <div className="flex items-center gap-3">
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center text-white text-xs font-bold ${isAllConsistent ? 'bg-brand-purple-soft' : 'bg-brand-navy'}`}>
                      {isAllConsistent ? <CheckFilled size={14} /> : mismatchCount}
                    </div>
                    <div>
                      <p className="font-semibold text-brand-navy">{item.field}</p>
                      <p className="text-xs text-slate-500">
                        {isAllConsistent ? '전 채널 일치' : `${mismatchCount}개 채널 불일치`}
                      </p>
                    </div>
                  </div>
                );
              })()}
              <ArrowRight
                size={16}
                className={`text-slate-400 transition-transform ${
                  expanded === i ? 'rotate-90' : ''
                }`}
              />
            </Button>

            {/* Expanded */}
            {expanded === i && (
              <div className="px-5 pb-5 border-t border-slate-100">
                <div className="grid gap-2 mt-4 mb-4">
                  {item.values.map((v) => (
                    <div
                      key={v.channel}
                      className={`flex items-center justify-between py-3 px-3 rounded-lg text-sm ${
                        v.isCorrect ? 'bg-brand-tint-purple/60' : 'bg-brand-rose-bg/60'
                      }`}
                    >
                      <span className="font-medium text-slate-700 min-w-[100px]">
                        {v.channel}
                      </span>
                      <span
                        className={`flex-1 text-right ${
                          v.isCorrect ? 'text-brand-purple-muted' : 'text-brand-rose'
                        }`}
                      >
                        {v.value}
                      </span>
                      <span className="ml-3">
                        {v.isCorrect ? (
                          <CheckFilled size={15} className="text-brand-purple-soft" />
                        ) : (
                          <CrossFilled size={15} className="text-brand-rose-mid" />
                        )}
                      </span>
                    </div>
                  ))}
                </div>

                {/* Impact */}
                <div className="rounded-xl bg-brand-earth-bg border border-brand-earth-soft p-4 mb-3">
                  <p className="text-xs font-semibold text-brand-earth uppercase tracking-wide mb-1 flex items-center gap-1">
                    <WarningFilled size={12} className="text-[#D4A872]" />
                    Impact
                  </p>
                  <p className="text-sm text-brand-earth">{item.impact}</p>
                </div>

                {/* Recommendation */}
                <div className="rounded-xl bg-brand-tint-purple border border-brand-tint-lavender p-4">
                  <p className="text-xs font-semibold text-brand-purple-muted uppercase tracking-wide mb-1 flex items-center gap-1">
                    <CheckFilled size={12} className="text-brand-purple-soft" />
                    Recommendation
                  </p>
                  <p className="text-sm text-brand-purple-muted">{item.recommendation}</p>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </motion.div>
  );
}

/* ─── 메인 컴포넌트 ─── */
export default function BrandingGuide({ data, clinicName }: BrandingGuideProps) {
  const [activeTab, setActiveTab] = useState<TabKey>('visual');

  return (
    <SectionWrapper
      id="branding-guide"
      title="Branding Guide"
      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>

      {activeTab === 'visual' && <VisualIdentityTab data={data} clinicName={clinicName} />}
      {activeTab === 'tone' && <ToneVoiceTab tone={data.toneOfVoice} />}
      {activeTab === 'channels' && <ChannelRulesTab channels={data.channelBranding} />}
      {activeTab === 'consistency' && (
        <BrandConsistencyTab inconsistencies={data.brandInconsistencies} />
      )}
    </SectionWrapper>
  );
}
