import { Skeleton, Tag, Typography } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import {
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, Legend,
  Area, AreaChart,
} from 'recharts';
import {
  IconCash, IconUsers, IconFileCheck, IconAlertTriangle, IconTrendingUp,
  IconTrendingDown, IconMinus, IconClock, IconArrowUpRight,
} from '@tabler/icons-react';
import PageContainer from '@/components/common/PageContainer';
import {
  COLOR_PRIMARY, COLOR_SUCCESS, COLOR_WARNING, COLOR_ERROR,
  COLOR_PRIMARY_LIGHT, GRAY, SHADOW,
} from '@/theme/tokens';

const { Text } = Typography;

// ────────────────────────────────────────────────
// Mock 데이터
// ────────────────────────────────────────────────

const KPI = [
  {
    title:    '모집수수료',
    value:    124_500_000,
    suffix:   '원',
    delta:    8.2,
    prevText: '전월比',
    color:    COLOR_PRIMARY,
    bg:       COLOR_PRIMARY_LIGHT,
    icon:     <IconCash size={20} />,
    format:   (v: number) => `${(v / 1_000_000).toFixed(1)}백만`,
  },
  {
    title:    '활성 설계사',
    value:    342,
    suffix:   '명',
    delta:    12,
    prevText: '전월比',
    color:    COLOR_SUCCESS,
    bg:       '#E8FAF3',
    icon:     <IconUsers size={20} />,
    format:   (v: number) => v.toLocaleString(),
  },
  {
    title:    '신계약',
    value:    87,
    suffix:   '건',
    delta:    -3.1,
    prevText: '전월比',
    color:    COLOR_WARNING,
    bg:       '#FFF6E6',
    icon:     <IconFileCheck size={20} />,
    format:   (v: number) => v.toLocaleString(),
  },
  {
    title:    '대사 차이',
    value:    3,
    suffix:   '건',
    delta:    1,
    prevText: '전월比',
    color:    COLOR_ERROR,
    bg:       '#FEF0F1',
    icon:     <IconAlertTriangle size={20} />,
    format:   (v: number) => v.toLocaleString(),
  },
  {
    title:    '확정 대기',
    value:    12,
    suffix:   '건',
    delta:    -2,
    prevText: '전월比',
    color:    '#7C3AED',
    bg:       '#F3EEFF',
    icon:     <IconClock size={20} />,
    format:   (v: number) => v.toLocaleString(),
  },
  {
    title:    '유지수수료',
    value:    82_300_000,
    suffix:   '원',
    delta:    3.1,
    prevText: '전월比',
    color:    '#0891B2',
    bg:       '#E0F7FA',
    icon:     <IconArrowUpRight size={20} />,
    format:   (v: number) => `${(v / 1_000_000).toFixed(1)}백만`,
  },
];

const MONTHLY = [
  { month: '12월', recruit: 95,  maintain: 70, chargeback: 5 },
  { month: '1월',  recruit: 105, maintain: 72, chargeback: 8 },
  { month: '2월',  recruit: 110, maintain: 75, chargeback: 6 },
  { month: '3월',  recruit: 118, maintain: 78, chargeback: 7 },
  { month: '4월',  recruit: 122, maintain: 80, chargeback: 9 },
  { month: '5월',  recruit: 125, maintain: 82, chargeback: 4 },
];

const TREND = [
  { month: '12월', net: 160 },
  { month: '1월',  net: 169 },
  { month: '2월',  net: 179 },
  { month: '3월',  net: 189 },
  { month: '4월',  net: 193 },
  { month: '5월',  net: 203 },
];

const STEPS = [
  { name: '데이터 수신',  status: 'done',     time: '02:14' },
  { name: '데이터 변환',  status: 'done',     time: '00:52' },
  { name: '대사 검증',    status: 'done',     time: '00:21' },
  { name: '모집수수료',   status: 'done',     time: '01:08' },
  { name: '유지수수료',   status: 'done',     time: '00:46' },
  { name: '환수/예외',    status: 'progress', time: '진행 중' },
  { name: '오버라이드',   status: 'pending' },
  { name: '집계',         status: 'pending' },
];

const ALERTS = [
  {
    tag: '대사불일치', color: 'error' as const,
    text: '삼성생명 5월 통보액 vs 시스템 계산액 3건 차이',
    time: '10분 전',
  },
  {
    tag: '파싱에러', color: 'warning' as const,
    text: '한화생명 raw 파일 12행 날짜 형식 오류 (log #4521)',
    time: '1시간 전',
  },
  {
    tag: '승인대기', color: 'processing' as const,
    text: '예외금액 원장 승인 대기 5건 (정산월 202605)',
    time: '3시간 전',
  },
];

// ────────────────────────────────────────────────
// 서브 컴포넌트
// ────────────────────────────────────────────────

function TrendIndicator({ delta }: { delta: number }) {
  if (delta > 0) {
    return (
      <span className="ga-kpi-trend-up" style={{ display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 12, fontWeight: 600 }}>
        <IconTrendingUp size={12} />
        +{Math.abs(delta).toFixed(1)}%
      </span>
    );
  }
  if (delta < 0) {
    return (
      <span className="ga-kpi-trend-down" style={{ display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 12, fontWeight: 600 }}>
        <IconTrendingDown size={12} />
        {delta.toFixed(1)}%
      </span>
    );
  }
  return (
    <span className="ga-kpi-trend-flat" style={{ display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 12 }}>
      <IconMinus size={12} />
      변동없음
    </span>
  );
}

function KpiCard({ k }: { k: typeof KPI[0] }) {
  return (
    <div
      style={{
        background:   '#ffffff',
        borderRadius: 16,
        border:       `1px solid ${GRAY[100]}`,
        boxShadow:    SHADOW.sm,
        padding:      '24px 28px',
        display:      'flex',
        flexDirection: 'column',
        gap:          16,
        height:       '100%',
        transition:   'box-shadow 0.2s ease',
      }}
    >
      {/* 상단: 아이콘 + 라벨 */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Text style={{ fontSize: 13, fontWeight: 500, color: GRAY[500] }}>
          {k.title}
        </Text>
        <div style={{
          width:          36, height: 36,
          borderRadius:   10,
          background:     k.bg,
          color:          k.color,
          display:        'flex',
          alignItems:     'center',
          justifyContent: 'center',
          flexShrink:     0,
        }}>
          {k.icon}
        </div>
      </div>

      {/* 중간: 큰 숫자 */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span style={{
          fontSize:   34,
          fontWeight: 700,
          color:      GRAY[800],
          lineHeight: 1,
          fontFeatureSettings: "'tnum'",
          fontVariantNumeric:  'tabular-nums',
        }}>
          {k.format(k.value)}
        </span>
        <Text style={{ fontSize: 14, color: GRAY[500], fontWeight: 400 }}>
          {k.suffix}
        </Text>
      </div>

      {/* 하단: 트렌드 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <TrendIndicator delta={k.delta} />
        <Text style={{ fontSize: 12, color: GRAY[400] }}>{k.prevText}</Text>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────
// 메인 컴포넌트
// ────────────────────────────────────────────────

export default function Dashboard() {
  return (
    <PageContainer
      title="대시보드"
      description="2026-05 정산 요약 · 실시간 배치 진행 · 알림"
    >

      {/* ── KPI 카드 6개 ── */}
      <div
        style={{
          display:             'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap:                 20,
          marginBottom:        24,
        }}
      >
        {KPI.map((k) => (
          <KpiCard key={k.title} k={k} />
        ))}
      </div>

      {/* ── 차트 2개 + 배치 진행 ── */}
      <ProCard gutter={[20, 20]} ghost wrap style={{ marginBottom: 20 }}>

        {/* 월별 수수료 바 차트 */}
        <ProCard
          colSpan={{ xs: 24, md: 16 }}
          title={<span style={{ fontSize: 15, fontWeight: 700, color: GRAY[800] }}>월별 수수료 추이</span>}
          subTitle={<span style={{ fontSize: 13, color: GRAY[400] }}>최근 6개월 (백만원)</span>}
          headerBordered
          style={{
            background:   '#ffffff',
            borderRadius: 16,
            border:       `1px solid ${GRAY[100]}`,
            boxShadow:    SHADOW.sm,
          }}
        >
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={MONTHLY} margin={{ top: 4, right: 8, left: -8, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke={GRAY[100]} vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 12, fill: GRAY[500] }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 12, fill: GRAY[500] }} axisLine={false} tickLine={false} />
              <Tooltip
                contentStyle={{
                  borderRadius: 12, border: `1px solid ${GRAY[100]}`,
                  boxShadow: SHADOW.md, fontSize: 13,
                }}
              />
              <Legend wrapperStyle={{ fontSize: 12, paddingTop: 8 }} />
              <Bar dataKey="recruit"    name="모집"  fill={COLOR_PRIMARY}  radius={[6, 6, 0, 0]} />
              <Bar dataKey="maintain"   name="유지"  fill={COLOR_SUCCESS}  radius={[6, 6, 0, 0]} />
              <Bar dataKey="chargeback" name="환수"  fill={COLOR_ERROR}    radius={[6, 6, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </ProCard>

        {/* 배치 진행 */}
        <ProCard
          colSpan={{ xs: 24, md: 8 }}
          title={<span style={{ fontSize: 15, fontWeight: 700, color: GRAY[800] }}>배치 진행</span>}
          subTitle={<span style={{ fontSize: 13, color: GRAY[400] }}>2026-05</span>}
          headerBordered
          style={{
            background:   '#ffffff',
            borderRadius: 16,
            border:       `1px solid ${GRAY[100]}`,
            boxShadow:    SHADOW.sm,
          }}
        >
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {STEPS.map((s, i) => {
              const isDone     = s.status === 'done';
              const isProgress = s.status === 'progress';
              const dotColor   = isDone ? COLOR_SUCCESS : isProgress ? COLOR_PRIMARY : GRAY[300];
              return (
                <div
                  key={i}
                  style={{
                    display:        'flex',
                    alignItems:     'center',
                    justifyContent: 'space-between',
                    padding:        '10px 0',
                    borderBottom:   i < STEPS.length - 1 ? `1px solid ${GRAY[100]}` : 'none',
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{
                      width:        8, height: 8,
                      borderRadius: '50%',
                      background:   dotColor,
                      flexShrink:   0,
                      boxShadow:    isProgress
                        ? `0 0 0 3px ${COLOR_PRIMARY}22`
                        : isDone ? `0 0 0 3px ${COLOR_SUCCESS}22` : 'none',
                    }} />
                    <Text style={{
                      fontSize:   13,
                      color:      s.status === 'pending' ? GRAY[400] : GRAY[700],
                      fontWeight: isProgress ? 700 : 400,
                    }}>
                      {s.name}
                    </Text>
                    {isProgress && (
                      <Tag color="blue" style={{ fontSize: 10, padding: '0 6px', margin: 0 }}>진행</Tag>
                    )}
                  </div>
                  <Text style={{ fontSize: 11, color: GRAY[400] }}>{s.time ?? '-'}</Text>
                </div>
              );
            })}
          </div>

          {/* 진행률 바 */}
          <div style={{ marginTop: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <Text style={{ fontSize: 13, color: GRAY[500] }}>전체 진행률</Text>
              <Text style={{ fontSize: 13, fontWeight: 700, color: COLOR_PRIMARY }}>62.5%</Text>
            </div>
            <div style={{
              height: 6, background: GRAY[100], borderRadius: 999, overflow: 'hidden',
            }}>
              <div style={{
                height: '100%', width: '62.5%',
                background:   COLOR_PRIMARY,
                borderRadius: 999,
                transition:   'width 0.5s ease',
              }} />
            </div>
          </div>
        </ProCard>
      </ProCard>

      {/* ── 실지급 추이 + 알림 ── */}
      <ProCard gutter={[20, 20]} ghost wrap>

        {/* 실지급 라인 차트 */}
        <ProCard
          colSpan={{ xs: 24, md: 12 }}
          title={<span style={{ fontSize: 15, fontWeight: 700, color: GRAY[800] }}>실지급 월별 추이</span>}
          subTitle={<span style={{ fontSize: 13, color: GRAY[400] }}>최근 6개월 누적 (백만원)</span>}
          headerBordered
          style={{
            background:   '#ffffff',
            borderRadius: 16,
            border:       `1px solid ${GRAY[100]}`,
            boxShadow:    SHADOW.sm,
          }}
        >
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={TREND} margin={{ top: 8, right: 8, left: -8, bottom: 0 }}>
              <defs>
                <linearGradient id="netGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%"  stopColor={COLOR_PRIMARY} stopOpacity={0.12} />
                  <stop offset="95%" stopColor={COLOR_PRIMARY} stopOpacity={0}    />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke={GRAY[100]} vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 12, fill: GRAY[500] }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 12, fill: GRAY[500] }} axisLine={false} tickLine={false} />
              <Tooltip
                contentStyle={{
                  borderRadius: 12, border: `1px solid ${GRAY[100]}`,
                  boxShadow: SHADOW.md, fontSize: 13,
                }}
              />
              <Area
                type="monotone"
                dataKey="net"
                name="실지급"
                stroke={COLOR_PRIMARY}
                strokeWidth={2}
                fill="url(#netGrad)"
                dot={{ fill: COLOR_PRIMARY, r: 3 }}
                activeDot={{ r: 5 }}
              />
            </AreaChart>
          </ResponsiveContainer>
        </ProCard>

        {/* 최근 알림 */}
        <ProCard
          colSpan={{ xs: 24, md: 12 }}
          title={<span style={{ fontSize: 15, fontWeight: 700, color: GRAY[800] }}>최근 알림</span>}
          headerBordered
          style={{
            background:   '#ffffff',
            borderRadius: 16,
            border:       `1px solid ${GRAY[100]}`,
            boxShadow:    SHADOW.sm,
          }}
          extra={
            <Text style={{ fontSize: 13, color: COLOR_PRIMARY, cursor: 'pointer', fontWeight: 500 }}>전체 보기</Text>
          }
        >
          {ALERTS.map((n, i) => (
            <div
              key={i}
              style={{
                display:      'flex',
                alignItems:   'flex-start',
                gap:          12,
                padding:      '14px 0',
                borderBottom: i < ALERTS.length - 1 ? `1px solid ${GRAY[100]}` : 'none',
              }}
            >
              <Tag
                color={n.color}
                style={{ flexShrink: 0, marginTop: 1 }}
              >
                {n.tag}
              </Tag>
              <Text style={{ flex: 1, fontSize: 13, color: GRAY[700], lineHeight: 1.5 }}>
                {n.text}
              </Text>
              <Text style={{ fontSize: 12, color: GRAY[400], whiteSpace: 'nowrap' }}>
                {n.time}
              </Text>
            </div>
          ))}

          <div style={{ marginTop: 12, display: 'none' }} className="ga-empty-state">
            <Text style={{ fontSize: 13, color: GRAY[400] }}>알림이 없습니다</Text>
          </div>
        </ProCard>
      </ProCard>

      {/* ── 스켈레톤 로딩 데모 (hidden) ── */}
      <div style={{ display: 'none' }}>
        <div className="ga-skeleton-card">
          <Skeleton active paragraph={{ rows: 3 }} />
        </div>
      </div>
    </PageContainer>
  );
}
