import { motion } from 'motion/react';
import { Instagram, ExternalLink } from 'lucide-react';
import { SectionWrapper } from './ui/SectionWrapper';
import { EmptyState } from './ui/EmptyState';
import { DiagnosisRow } from './ui/DiagnosisRow';
import type { InstagramAudit as InstagramAuditType, InstagramAccount } from '@/features/report/types/report';

interface InstagramAuditProps {
  data: InstagramAuditType;
}

function formatNumber(n: number): string {
  return n.toLocaleString();
}

function AccountCard({ account, index }: { key?: string | number; account: InstagramAccount; index: number }) {
  const langColor = account.language === 'KR'
    ? 'bg-slate-100 text-slate-700'
    : 'bg-[#EFF0FF] text-[#3A3F7C]';

  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 }}
    >
      {/* Language badge + handle */}
      <div className="flex items-center gap-2 mb-4">
        <span className={`text-xs font-medium px-3 py-1 rounded-full ${langColor}`}>
          {account.label}
        </span>
        <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center">
          <Instagram size={16} className="text-white" />
        </div>
      </div>

      <h3 className="font-bold text-lg text-[#0A1128] mb-1">
        {account.handle ? (
          <a
            href={`https://instagram.com/${account.handle.replace(/^@/, '')}`}
            target="_blank"
            rel="noopener noreferrer"
            className="hover:text-[#6C5CE7] inline-flex items-center gap-1"
          >
            {account.handle}
            <ExternalLink size={13} className="text-[#6C5CE7]" />
          </a>
        ) : account.handle}
      </h3>
      <p className="text-xs text-slate-500 mb-4">{account.category}</p>

      {/* Compact metrics */}
      <div className="grid grid-cols-3 gap-2 mb-4">
        <div className="rounded-xl bg-slate-50 p-3 text-center">
          <p className="text-xs text-slate-500">게시물</p>
          <p className="text-lg font-bold text-[#0A1128]">{formatNumber(account.posts)}</p>
        </div>
        <div className="rounded-xl bg-slate-50 p-3 text-center">
          <p className="text-xs text-slate-500">팔로워</p>
          <p className="text-lg font-bold text-[#0A1128]">{formatNumber(account.followers)}</p>
        </div>
        <div className="rounded-xl bg-slate-50 p-3 text-center">
          <p className="text-xs text-slate-500">팔로잉</p>
          <p className="text-lg font-bold text-[#0A1128]">{formatNumber(account.following)}</p>
        </div>
      </div>

      {/* Format */}
      <div className="space-y-2 mb-4">
        <div className="flex items-center justify-between text-sm">
          <span className="text-slate-500">콘텐츠 포맷</span>
          <span className="font-medium text-[#0A1128]">{account.contentFormat}</span>
        </div>
      </div>

      {/* Highlights */}
      {account.highlights.length > 0 && (
        <div className="mb-4">
          <p className="text-xs text-slate-500 mb-2">하이라이트</p>
          <div className="flex flex-wrap gap-2">
            {account.highlights.map((h) => (
              <span
                key={h}
                className="rounded-full bg-white/60 backdrop-blur-sm border border-white/40 px-3 py-1 text-sm font-medium text-slate-700"
              >
                {h}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Bio */}
      {account.bio && (
        <div className="rounded-xl bg-slate-50 p-3">
          <p className="text-xs text-slate-400 mb-1">Bio</p>
          <p className="text-sm text-slate-600 whitespace-pre-line">{account.bio}</p>
        </div>
      )}
    </motion.div>
  );
}

export default function InstagramAudit({ data }: InstagramAuditProps) {
  const hasAccounts = data.accounts.length > 0 && data.accounts.some(a => a.handle || a.followers > 0);

  return (
    <SectionWrapper id="instagram-audit" title="Instagram Analysis" subtitle="인스타그램 채널 분석">
      {!hasAccounts && data.diagnosis.length === 0 && (
        <EmptyState
          message="Instagram 계정 데이터 수집 중"
          subtext="채널 데이터 보강이 완료되면 계정 정보와 분석 결과가 표시됩니다."
        />
      )}

      {/* Account cards */}
      {hasAccounts && (
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        {data.accounts.map((account, i) => (
          <AccountCard key={account.handle || i} account={account} index={i} />
        ))}
      </div>
      )}

      {/* Diagnosis */}
      {data.diagnosis.length > 0 && (
        <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: 0.3 }}
        >
          <p className="text-sm font-semibold text-slate-700 mb-4">진단 결과</p>
          {data.diagnosis.map((item, i) => (
            <DiagnosisRow key={i} category={item.category} detail={item.detail} severity={item.severity} evidenceIds={item.evidenceIds} />
          ))}
        </motion.div>
      )}
    </SectionWrapper>
  );
}
