/**
 * 디자인 시스템 카탈로그 페이지.
 *
 * 토큰(색·폰트·여백·radius) + 공통 컴포넌트를 한 화면에 모아서
 * 일관성·누락·충돌을 눈으로 빠르게 확인하는 용도.
 *
 * 운영 환경에서 노출하지 않으려면 라우트를 dev-only로 분리하거나
 * import.meta.env.DEV 가드 추가.
 */
import { useState } from 'react';
import { Bell, Check, Heart, Settings, Trash2 } from 'lucide-react';
import { Button } from '@/shared/ui/button';
import { Badge } from '@/shared/ui/badge';
import { Input } from '@/shared/ui/input';
import { Textarea } from '@/shared/ui/textarea';
import { Label } from '@/shared/ui/label';
import { Checkbox } from '@/shared/ui/checkbox';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/shared/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/shared/ui/tabs';
import { Alert, AlertDescription, AlertTitle } from '@/shared/ui/alert';
import { Separator } from '@/shared/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/shared/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/shared/ui/select';
import * as FilledIcons from '@/shared/icons/FilledIcons';
import { PageContainer } from '@/shared/ui/page-container';

/* ─────────────── 작은 보조 컴포넌트 ─────────────── */

function Swatch({
  name,
  value,
  textOn = 'dark',
}: {
  name: string;
  value: string;
  textOn?: 'dark' | 'light';
}) {
  return (
    <div className="flex flex-col gap-2">
      <div
        className="h-20 rounded-xl border border-slate-200 flex items-end p-2"
        style={{ background: value }}
      >
        <span
          className={`text-[10px] font-mono ${
            textOn === 'dark' ? 'text-white/80' : 'text-slate-700'
          }`}
        >
          {value}
        </span>
      </div>
      <div className="text-xs font-mono text-slate-600">{name}</div>
    </div>
  );
}

function StatusPill({
  label,
  bg,
  text,
  border,
  dot,
}: {
  label: string;
  bg: string;
  text: string;
  border: string;
  dot: string;
}) {
  return (
    <div className="flex flex-col gap-3">
      <div
        className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium border w-fit"
        style={{ background: bg, color: text, borderColor: border }}
      >
        <span className="w-2 h-2 rounded-full" style={{ background: dot }} />
        {label}
      </div>
      <div className="grid grid-cols-2 gap-1 text-[10px] font-mono text-slate-500">
        <span>bg: {bg}</span>
        <span>text: {text}</span>
        <span>border: {border}</span>
        <span>dot: {dot}</span>
      </div>
    </div>
  );
}

function SectionHeader({ title, desc }: { title: string; desc?: string }) {
  return (
    <div className="mb-8">
      <h2 className="font-serif text-3xl font-bold">{title}</h2>
      {desc && <p className="text-sm text-slate-500 mt-2">{desc}</p>}
    </div>
  );
}

function Section({
  title,
  desc,
  dark = false,
  children,
}: {
  title: string;
  desc?: string;
  dark?: boolean;
  children: React.ReactNode;
}) {
  return (
    <section className={`py-16 px-6 ${dark ? 'bg-primary-900 text-white' : ''}`}>
      <PageContainer className="px-0">
        <SectionHeader title={title} desc={desc} />
        {children}
      </PageContainer>
    </section>
  );
}

/* ─────────────── 메인 페이지 ─────────────── */

export default function ComponentsPage() {
  const [checked, setChecked] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);

  return (
    <div className="pt-20 bg-white">
      {/* Hero */}
      <div className="px-6 py-20 bg-gradient-to-br from-[#fff3eb] via-[#e4cfff] to-[#f5f9ff]">
        <PageContainer className="px-0">
          <p className="font-mono text-xs text-slate-600 uppercase tracking-widest mb-3">
            Design System
          </p>
          <h1 className="font-serif text-5xl font-bold mb-3">컴포넌트 카탈로그</h1>
          <p className="text-slate-600 max-w-2xl">
            토큰·폰트·버튼·카드·폼·다이얼로그 등 공통 요소를 한 화면에서 점검. 새로 만들 때 이 페이지에 추가해두면
            디자이너/개발자가 같은 곳을 봅니다.
          </p>
        </PageContainer>
      </div>

      {/* 1. Brand Colors */}
      <Section title="1. 브랜드 컬러" desc="브랜드 팔레트 전체. 토큰 이름과 hex를 같이 표시.">
        <div className="space-y-10">
          <div>
            <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4">
              Purple family
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
              <Swatch name="brand-purple" value="#4F1DA1" />
              <Swatch name="brand-purple-deep" value="#021341" />
              <Swatch name="brand-purple-vivid" value="#6C5CE7" />
              <Swatch name="brand-purple-muted" value="#4A3A7C" />
              <Swatch name="brand-purple-soft" value="#9B8AD4" />
              <Swatch name="brand-purple-faint" value="#3A3F7C" />
            </div>
          </div>

          <div>
            <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4">
              Navy (텍스트·배경)
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
              <Swatch name="brand-navy" value="#0A1128" />
              <Swatch name="brand-navy-soft" value="#1A2B5E" />
              <Swatch name="brand-navy-faint" value="#F4F6FB" textOn="light" />
            </div>
          </div>

          <div>
            <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4">
              Tints (배경·카드)
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
              <Swatch name="brand-tint-purple" value="#F3F0FF" textOn="light" />
              <Swatch name="brand-tint-lavender" value="#D5CDF5" textOn="light" />
              <Swatch name="brand-tint-violet" value="#EFF0FF" textOn="light" />
              <Swatch name="brand-tint-orchid" value="#C084CF" />
            </div>
          </div>

          <div>
            <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4">
              Warm tones (Rose / Earth)
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
              <Swatch name="brand-rose" value="#7C3A4B" />
              <Swatch name="brand-rose-mid" value="#D4889A" />
              <Swatch name="brand-rose-soft" value="#F5D5DC" textOn="light" />
              <Swatch name="brand-rose-bg" value="#FFF0F0" textOn="light" />
              <Swatch name="brand-earth" value="#7C5C3A" />
              <Swatch name="brand-earth-mid" value="#D4A872" />
              <Swatch name="brand-earth-soft" value="#F5E0C5" textOn="light" />
              <Swatch name="brand-earth-bg" value="#FFF6ED" textOn="light" />
            </div>
          </div>

          <div>
            <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4">
              Periwinkle (info) + Gradient anchors
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
              <Swatch name="brand-periwinkle" value="#7A84D4" />
              <Swatch name="brand-periwinkle-border" value="#C5CBF5" textOn="light" />
              <Swatch name="brand-grad-peach" value="#FFF3EB" textOn="light" />
              <Swatch name="brand-grad-violet" value="#E4CFFF" textOn="light" />
              <Swatch name="brand-grad-sky" value="#F5F9FF" textOn="light" />
            </div>
          </div>
        </div>
      </Section>

      <Separator />

      {/* 2. Status semantic */}
      <Section
        title="2. 상태 색상"
        desc="critical / warning / good / info — bg·text·border·dot 한 세트로 사용."
      >
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <StatusPill
            label="Critical"
            bg="#FFF0F0"
            text="#7C3A4B"
            border="#F5D5DC"
            dot="#D4889A"
          />
          <StatusPill
            label="Warning"
            bg="#FFF6ED"
            text="#7C5C3A"
            border="#F5E0C5"
            dot="#D4A872"
          />
          <StatusPill
            label="Good"
            bg="#F3F0FF"
            text="#4A3A7C"
            border="#D5CDF5"
            dot="#9B8AD4"
          />
          <StatusPill
            label="Info"
            bg="#EFF0FF"
            text="#3A3F7C"
            border="#C5CBF5"
            dot="#7A84D4"
          />
        </div>
      </Section>

      <Separator />

      {/* 3. Typography */}
      <Section
        title="3. 타이포그래피"
        desc="영문 헤딩 = Playfair Display, 한글·본문 = Pretendard Variable."
      >
        <div className="space-y-6">
          <div className="border-b border-slate-100 pb-4">
            <h1 className="font-serif text-6xl font-bold">Heading 1 — 6xl serif</h1>
            <p className="text-xs font-mono text-slate-400 mt-1">font-serif text-6xl font-bold</p>
          </div>
          <div className="border-b border-slate-100 pb-4">
            <h2 className="font-serif text-4xl font-bold">Heading 2 — 4xl serif</h2>
            <p className="text-xs font-mono text-slate-400 mt-1">font-serif text-4xl font-bold</p>
          </div>
          <div className="border-b border-slate-100 pb-4">
            <h3 className="font-serif text-2xl font-bold">Heading 3 — 2xl serif</h3>
            <p className="text-xs font-mono text-slate-400 mt-1">font-serif text-2xl font-bold</p>
          </div>
          <div className="border-b border-slate-100 pb-4">
            <p className="text-base">
              본문 — Pretendard Variable. INFINITH는 프리미엄 의료 비즈니스를 위한 AI 마케팅 자동화 SaaS입니다.
            </p>
            <p className="text-xs font-mono text-slate-400 mt-1">text-base</p>
          </div>
          <div className="border-b border-slate-100 pb-4">
            <p className="text-sm text-slate-600">
              작은 본문 / 캡션 — text-sm text-slate-600
            </p>
          </div>
          <div className="border-b border-slate-100 pb-4">
            <p className="text-xs font-mono text-slate-500">font-mono · text-xs · 메타 정보용</p>
          </div>
          <div>
            <p className="font-serif text-4xl font-black tracking-[0.05em] bg-gradient-to-r from-[#4F1DA1] to-[#021341] bg-clip-text text-transparent">
              INFINITH
            </p>
            <p className="text-xs font-mono text-slate-400 mt-1">로고 스타일</p>
          </div>
        </div>
      </Section>

      <Separator />

      {/* 4. Buttons */}
      <Section title="4. 버튼" desc="5가지 변형 × 4가지 사이즈.">
        <div className="space-y-8">
          {(['default', 'destructive', 'outline', 'secondary', 'ghost', 'link'] as const).map(
            (variant) => (
              <div key={variant}>
                <p className="text-xs font-mono text-slate-500 mb-3">variant=&quot;{variant}&quot;</p>
                <div className="flex flex-wrap items-center gap-3">
                  <Button variant={variant} size="lg">
                    Large
                  </Button>
                  <Button variant={variant} size="default">
                    Default
                  </Button>
                  <Button variant={variant} size="sm">
                    Small
                  </Button>
                  <Button variant={variant} size="xs">
                    Extra Small
                  </Button>
                  <Button variant={variant} size="icon" aria-label="settings">
                    <Settings />
                  </Button>
                  <Button variant={variant} disabled>
                    Disabled
                  </Button>
                </div>
              </div>
            ),
          )}
        </div>
      </Section>

      <Separator />

      {/* 5. Badges */}
      <Section title="5. 배지" desc="라벨·태그·상태 표시.">
        <div className="flex flex-wrap items-center gap-3">
          <Badge>Default</Badge>
          <Badge variant="secondary">Secondary</Badge>
          <Badge variant="destructive">Destructive</Badge>
          <Badge variant="outline">Outline</Badge>
          <Badge variant="ghost">Ghost</Badge>
          <Badge>
            <Check />
            완료
          </Badge>
          <Badge variant="destructive">
            <Heart />
            긴급
          </Badge>
        </div>
      </Section>

      <Separator />

      {/* 6. Forms */}
      <Section title="6. 폼 컴포넌트" desc="Input / Textarea / Select / Checkbox / Label.">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl">
          <div className="space-y-2">
            <Label htmlFor="dev-input">병원 URL</Label>
            <Input id="dev-input" placeholder="https://example.com" />
            <p className="text-xs text-slate-500">힌트 텍스트. 형식 안내.</p>
          </div>
          <div className="space-y-2">
            <Label htmlFor="dev-input-err">에러 상태</Label>
            <Input id="dev-input-err" aria-invalid placeholder="잘못된 입력" />
            <p className="text-xs text-status-critical-text">올바른 URL을 입력해주세요.</p>
          </div>
          <div className="space-y-2 md:col-span-2">
            <Label htmlFor="dev-textarea">설명</Label>
            <Textarea id="dev-textarea" placeholder="여러 줄 입력..." rows={4} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="dev-select">플랜</Label>
            <Select>
              <SelectTrigger id="dev-select">
                <SelectValue placeholder="플랜 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="free">Free</SelectItem>
                <SelectItem value="starter">Starter</SelectItem>
                <SelectItem value="pro">Professional</SelectItem>
                <SelectItem value="agency">Agency</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-3">
            <Label>약관 동의</Label>
            <div className="flex items-center gap-2">
              <Checkbox
                id="dev-check"
                checked={checked}
                onCheckedChange={(v) => setChecked(v === true)}
              />
              <Label htmlFor="dev-check" className="font-normal cursor-pointer">
                개인정보 처리방침에 동의합니다
              </Label>
            </div>
          </div>
        </div>
      </Section>

      <Separator />

      {/* 7. Cards */}
      <Section title="7. 카드" desc="기본 카드 + glass-card 효과.">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card>
            <CardHeader>
              <CardTitle>기본 카드</CardTitle>
              <CardDescription>shadcn Card 컴포넌트.</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-slate-600">
                헤더·설명·내용 영역으로 구성. 그림자와 라운드는 토큰에서 가져옴.
              </p>
            </CardContent>
          </Card>

          <div className="glass-card p-6">
            <h3 className="font-serif text-xl font-bold mb-2">Glass Card</h3>
            <p className="text-sm text-slate-600">
              반투명 + blur. 그라디언트 배경 위에 띄울 때 사용.
            </p>
            <p className="text-xs font-mono text-slate-400 mt-3">.glass-card</p>
          </div>

          <Card className="border-brand-purple-vivid/40 bg-brand-tint-purple">
            <CardHeader>
              <CardTitle>강조 카드</CardTitle>
              <CardDescription>중요 정보 박스.</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-brand-purple-muted">
                background·border 컬러 토큰으로 강조 표시.
              </p>
            </CardContent>
          </Card>
        </div>
      </Section>

      <Separator />

      {/* 8. Alerts */}
      <Section title="8. 알림 박스" desc="페이지 내 인라인 알림.">
        <div className="space-y-4 max-w-3xl">
          <Alert>
            <Bell className="h-4 w-4" />
            <AlertTitle>알림</AlertTitle>
            <AlertDescription>
              분석이 시작되었습니다. 1~3분 소요됩니다.
            </AlertDescription>
          </Alert>
          <Alert variant="destructive">
            <Trash2 className="h-4 w-4" />
            <AlertTitle>에러</AlertTitle>
            <AlertDescription>
              올바른 URL을 입력해주세요. (variant=&quot;destructive&quot;)
            </AlertDescription>
          </Alert>
        </div>
      </Section>

      <Separator />

      {/* 9. Tabs */}
      <Section title="9. 탭" desc="Tabs / TabsList / TabsTrigger / TabsContent.">
        <Tabs defaultValue="overview" className="max-w-3xl">
          <TabsList>
            <TabsTrigger value="overview">개요</TabsTrigger>
            <TabsTrigger value="channels">채널</TabsTrigger>
            <TabsTrigger value="kpi">KPI</TabsTrigger>
          </TabsList>
          <TabsContent value="overview" className="p-6 border border-slate-200 rounded-xl mt-4">
            <p className="text-sm text-slate-600">개요 탭 내용입니다.</p>
          </TabsContent>
          <TabsContent value="channels" className="p-6 border border-slate-200 rounded-xl mt-4">
            <p className="text-sm text-slate-600">채널 탭 내용입니다.</p>
          </TabsContent>
          <TabsContent value="kpi" className="p-6 border border-slate-200 rounded-xl mt-4">
            <p className="text-sm text-slate-600">KPI 탭 내용입니다.</p>
          </TabsContent>
        </Tabs>
      </Section>

      <Separator />

      {/* 10. Dialog */}
      <Section title="10. 다이얼로그" desc="모달 — Dialog / DialogTrigger 패턴.">
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button>다이얼로그 열기</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>정말 삭제할까요?</DialogTitle>
              <DialogDescription>
                이 작업은 되돌릴 수 없습니다. 연결된 데이터도 함께 삭제됩니다.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button variant="outline" onClick={() => setDialogOpen(false)}>
                취소
              </Button>
              <Button variant="destructive" onClick={() => setDialogOpen(false)}>
                삭제
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </Section>

      {/* 11. 다크 섹션 (룰 데모) */}
      <Section
        title="11. 다크 섹션 (규칙 데모)"
        desc="다크 배경(#0A1128) 위에는 흰 카드(bg-white + 그림자) 사용. glass-card 아님."
        dark
      >
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="bg-white rounded-2xl shadow-lg p-6">
            <h3 className="font-serif text-xl font-bold mb-2 text-brand-navy">흰 카드</h3>
            <p className="text-sm text-slate-600">
              다크 섹션 위에는 이 패턴. glass-card 금지.
            </p>
          </div>
          <div className="bg-white rounded-2xl shadow-lg p-6">
            <Badge>완료</Badge>
            <p className="mt-3 text-sm text-slate-600">배지·텍스트는 라이트 카드 안에서 정상 표시.</p>
          </div>
          <div className="bg-white rounded-2xl shadow-lg p-6">
            <Button>내부 버튼</Button>
            <p className="mt-3 text-sm text-slate-600">버튼도 카드 내부에 두면 안전.</p>
          </div>
        </div>
      </Section>

      <Separator />

      {/* 12. Lucide icons */}
      <Section title="12. 아이콘 — Lucide" desc="기본 아이콘 세트. line 스타일.">
        <div className="grid grid-cols-4 md:grid-cols-8 gap-4">
          {[
            { icon: Bell, name: 'Bell' },
            { icon: Check, name: 'Check' },
            { icon: Heart, name: 'Heart' },
            { icon: Settings, name: 'Settings' },
            { icon: Trash2, name: 'Trash2' },
          ].map(({ icon: Icon, name }) => (
            <div
              key={name}
              className="flex flex-col items-center gap-2 p-4 border border-slate-200 rounded-xl"
            >
              <Icon className="w-6 h-6 text-brand-navy" />
              <span className="text-xs font-mono text-slate-500">{name}</span>
            </div>
          ))}
        </div>
      </Section>

      <Separator />

      {/* 13. Filled Icons */}
      <Section
        title="13. 아이콘 — FilledIcons"
        desc="브랜드 전용 채워진 SVG 아이콘 세트. 다크 섹션이나 카드 헤더에서 강조용."
      >
        <div className="grid grid-cols-4 md:grid-cols-8 gap-4">
          {Object.entries(FilledIcons)
            .filter(([, v]) => typeof v === 'function')
            .map(([name, Comp]) => {
              const Icon = Comp as React.ComponentType<{ size?: number; className?: string }>;
              return (
                <div
                  key={name}
                  className="flex flex-col items-center gap-2 p-4 border border-slate-200 rounded-xl"
                >
                  <Icon size={28} className="text-brand-purple-vivid" />
                  <span className="text-[10px] font-mono text-slate-500 text-center break-all">
                    {name}
                  </span>
                </div>
              );
            })}
        </div>
      </Section>

      {/* Footer note */}
      <div className="px-6 py-12 bg-slate-50 text-center">
        <p className="text-xs font-mono text-slate-500">
          design system catalog · /dev/components · 새 컴포넌트 추가 시 여기도 같이 등록할 것
        </p>
      </div>
    </div>
  );
}
