'use client';

import { useState, useEffect } from 'react';
import {
  ExternalLink,
  Copy,
  Check,
  ChevronDown,
  ChevronRight,
  RefreshCw,
  Link,
  Home,
  Monitor,
  BarChart3,
  FileText,
  type LucideIcon,
} from 'lucide-react';

// Lucide 아이콘 매핑 (이모지 대신 사용 - Chrome DevTools MCP JSON 직렬화 오류 방지)
const iconComponents: Record<string, LucideIcon> = {
  Home,
  Monitor,
  BarChart3,
  FileText,
};

function CategoryIcon({ name, className }: { name: string; className?: string }) {
  const IconComponent = iconComponents[name] || FileText;
  return <IconComponent className={className} />;
}

export interface UrlItem {
  name: string;
  url: string;
  status?: string;
}

export interface UrlCategory {
  title: string;
  icon: string;
  items: UrlItem[];
  subCategories?: {
    title: string;
    items: UrlItem[];
  }[];
}

interface TestUrlsClientProps {
  initialData: UrlCategory[];
  lastUpdated: string;
}

function UrlCard({ item, baseUrl }: { item: UrlItem; baseUrl: string }) {
  const [copied, setCopied] = useState(false);
  const fullUrl = `${baseUrl}${item.url}`;

  const handleCopy = async (e: React.MouseEvent) => {
    e.stopPropagation();
    await navigator.clipboard.writeText(fullUrl);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleOpen = () => {
    window.open(fullUrl, '_blank');
  };

  return (
    <div
      onClick={handleOpen}
      className="group flex items-center justify-between p-3 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500 hover:shadow-md transition-all cursor-pointer"
    >
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="font-medium text-gray-900 dark:text-white truncate">
            {item.name}
          </span>
          {item.status && (
            <span className="text-xs px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700">
              {item.status}
            </span>
          )}
        </div>
        <p className="text-sm text-gray-500 dark:text-gray-400 truncate mt-0.5">
          {item.url}
        </p>
      </div>
      <div className="flex items-center gap-1 ml-2">
        <button
          onClick={handleCopy}
          className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
          title="URL 복사"
        >
          {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
        </button>
        <ExternalLink className="w-4 h-4 text-gray-400 group-hover:text-blue-500 transition-colors" />
      </div>
    </div>
  );
}

function CategorySection({ category, baseUrl }: { category: UrlCategory; baseUrl: string }) {
  const [expanded, setExpanded] = useState(true);
  const [subExpanded, setSubExpanded] = useState<Record<string, boolean>>({});

  const toggleSub = (title: string) => {
    setSubExpanded((prev) => ({ ...prev, [title]: !prev[title] }));
  };

  const totalItems = category.items.length +
    (category.subCategories?.reduce((acc, sub) => acc + sub.items.length, 0) || 0);

  if (totalItems === 0) return null;

  return (
    <div className="mb-6">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 w-full text-left mb-3"
      >
        {expanded ? (
          <ChevronDown className="w-5 h-5 text-gray-500" />
        ) : (
          <ChevronRight className="w-5 h-5 text-gray-500" />
        )}
        <CategoryIcon name={category.icon} className="w-5 h-5 text-blue-500" />
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
          {category.title}
        </h2>
        <span className="text-sm text-gray-500 ml-auto">
          {totalItems} 링크
        </span>
      </button>

      {expanded && (
        <div className="pl-7 space-y-4">
          {category.items.length > 0 && (
            <div className="grid gap-2">
              {category.items.map((item) => (
                <UrlCard key={item.url} item={item} baseUrl={baseUrl} />
              ))}
            </div>
          )}

          {category.subCategories?.map((sub) => (
            <div key={sub.title} className="mt-3">
              <button
                onClick={() => toggleSub(sub.title)}
                className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-2 hover:text-gray-900 dark:hover:text-white"
              >
                {subExpanded[sub.title] !== false ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
                {sub.title}
                <span className="text-xs text-gray-400">({sub.items.length})</span>
              </button>
              {subExpanded[sub.title] !== false && (
                <div className="grid gap-2 pl-6">
                  {sub.items.map((item) => (
                    <UrlCard key={item.url} item={item} baseUrl={baseUrl} />
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default function ConstructionTestUrlsClient({ initialData, lastUpdated }: TestUrlsClientProps) {
  const [baseUrl, setBaseUrl] = useState('http://localhost:3000');
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    if (typeof window !== 'undefined') {
      setBaseUrl(window.location.origin);
    }
  }, []);

  // 검색 필터링
  const filteredData = initialData
    .map((category) => ({
      ...category,
      items: category.items.filter(
        (item) =>
          item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          item.url.toLowerCase().includes(searchTerm.toLowerCase())
      ),
      subCategories: category.subCategories?.map((sub) => ({
        ...sub,
        items: sub.items.filter(
          (item) =>
            item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            item.url.toLowerCase().includes(searchTerm.toLowerCase())
        ),
      })).filter((sub) => sub.items.length > 0),
    }))
    .filter(
      (category) =>
        category.items.length > 0 || (category.subCategories && category.subCategories.length > 0)
    );

  const totalLinks = initialData.reduce(
    (acc, cat) =>
      acc +
      cat.items.length +
      (cat.subCategories?.reduce((subAcc, sub) => subAcc + sub.items.length, 0) || 0),
    0
  );

  const handleRefresh = () => {
    window.location.reload();
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <h1 className="flex items-center gap-2 text-2xl font-bold text-gray-900 dark:text-white mb-2">
              <Link className="w-6 h-6 text-blue-500" />
              주일기업 테스트 URL 목록
            </h1>
            <button
              onClick={handleRefresh}
              className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
              title="새로고침 (md 파일 변경사항 반영)"
            >
              <RefreshCw className="w-4 h-4" />
              새로고침
            </button>
          </div>
          <p className="text-gray-600 dark:text-gray-400">
            주일기업용 백엔드 메뉴 연동 전 테스트용 직접 접근 URL ({totalLinks}개)
          </p>
          <p className="text-xs text-gray-400 mt-1">
            클릭하면 새 탭에서 열립니다 - 최종 업데이트: {lastUpdated}
          </p>
          <p className="text-xs text-green-600 dark:text-green-400 mt-1">
            md 파일 수정 시 자동 반영됩니다
          </p>
        </div>

        {/* Search & Base URL */}
        <div className="flex gap-4 mb-6">
          <input
            type="text"
            placeholder="페이지 또는 URL 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <div className="flex items-center gap-2 px-3 py-2 bg-white dark:bg-gray-800 rounded-lg border border-gray-300 dark:border-gray-600">
            <span className="text-sm text-gray-500">Base:</span>
            <input
              type="text"
              value={baseUrl}
              onChange={(e) => setBaseUrl(e.target.value)}
              className="w-48 text-sm bg-transparent text-gray-900 dark:text-white focus:outline-none"
            />
          </div>
        </div>

        {/* Categories */}
        <div className="space-y-2">
          {filteredData.map((category) => (
            <CategorySection key={category.title} category={category} baseUrl={baseUrl} />
          ))}
        </div>

        {filteredData.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            검색 결과가 없습니다.
          </div>
        )}

        {/* Footer */}
        <div className="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700 text-center text-sm text-gray-500">
          <p>
            데이터 소스: <code className="bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded">claudedocs/[REF] construction-pages-test-urls.md</code>
          </p>
          <p className="mt-1 text-green-600 dark:text-green-400">
            md 파일 수정 후 새로고침하면 자동 반영!
          </p>
        </div>
      </div>
    </div>
  );
}
