import { ExternalLink, LayoutDashboard, ArrowUpRight } from 'lucide-react';
import { useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { useNavigate } from '@tanstack/react-router';

interface InfoItem {
  title: string;
  value: string;
  description: string;
}

interface DashCardProps {
  isCNB: boolean;
  liveData: { list?: InfoItem[] } | null;
}

const DEFAULT_SHOW_COUNT = 12;

function isUrl(value: string): boolean {
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
}

export function DashCard({ isCNB, liveData }: DashCardProps) {
  const [expanded, setExpanded] = useState(false);
  if (!isCNB || !liveData?.list?.length) return null;
  const data = useMemo(() => {
    if (!liveData?.list) return { docs: null, list: [] };
    const docs = liveData.list.find((item) => item.title === 'docs');
    const list = liveData.list.filter((item) => item.title !== 'docs');
    return { docs, list }
  }, [liveData]);

  const showList = expanded ? data.list : data.list.slice(0, DEFAULT_SHOW_COUNT);
  const hasMore = data.list.length > DEFAULT_SHOW_COUNT;

  return (
    <div className="mb-4">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
        {showList.map((item) => (
          <div
            key={item.title}
            className="border rounded-lg p-3 hover:border-primary/50 transition-colors"
          >
            <div className="text-xs text-muted-foreground mb-1">{item.title}</div>
            {item.value ? (
              isUrl(item.value) ? (
                <a
                  href={item.value}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-500 hover:underline text-sm flex items-center gap-1"
                >
                  <span className="truncate">{item.value}</span>
                  <ExternalLink className="h-3 w-3 shrink-0" />
                </a>
              ) : (
                <div className="text-sm truncate" title={item.value}>{item.value}</div>
              )
            ) : (
              <div className="text-muted-foreground text-sm">(空)</div>
            )}
            {item.description && (
              <div className="text-xs text-muted-foreground mt-1 truncate" title={item.description}>
                {item.description}
              </div>
            )}
          </div>
        ))}
      </div>
      {hasMore && (
        <div className="flex justify-center mt-3">
          <Button variant="ghost" size="sm" onClick={() => setExpanded(!expanded)}>
            {expanded ? (
              <>
                <ChevronUp className="h-4 w-4 mr-1" />
                收起
              </>
            ) : (
              <>
                <ChevronDown className="h-4 w-4 mr-1" />
                更多 ({data.list.length - DEFAULT_SHOW_COUNT})
              </>
            )}
          </Button>
        </div>
      )}
    </div>
  );
}

export const DashTitle = () => {
  const navigate = useNavigate();
  const toCNBBoard = () => {
    navigate({ to: '/cnb-board' });
  }
  return (
    <div className="text-lg font-semibold mb-2 flex items-center gap-2">
      <LayoutDashboard className="h-5 w-5" />
      CNB Board 实时信息
      <Button
        variant="ghost"
        onClick={toCNBBoard}
        className="text-muted-foreground hover:text-primary cursor-pointer"
        title='更多'
      >
        <ArrowUpRight className="h-4 w-4" />
      </Button>
    </div>
  );
}