import { useState, useCallback } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import GithubSlugger from 'github-slugger';
import { Copy, Check, BookOpen, Hash, User, Terminal } from 'lucide-react';
import { CategoryBadge } from '@/components/CategoryBadge';
import { Footer } from '@/components/Footer';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import { Skill } from '@/types/skills';

export interface TocItem {
  id: string;
  text: string;
  level: number;
}

export function extractToc(content: string): TocItem[] {
  const toc: TocItem[] = [];
  const slugger = new GithubSlugger();
  const headingRegex = /^(#{1,6})\s+(.+)$/gm;
  let match;

  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length;
    const text = match[2].trim();
    const id = slugger.slug(text);
    toc.push({ id, text, level });
  }

  return toc;
}

interface SkillViewerProps {
  skill: Skill | null;
  content: string | null;
  isLoading: boolean;
}

function useCopyText(text: string) {
  const [copied, setCopied] = useState(false);

  const copy = useCallback(async () => {
    if (!text) return;
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, [text]);

  return { copied, copy };
}

function CopyCodeButton({ text }: { text: string }) {
  const { copied, copy } = useCopyText(text);

  return (
    <button
      type="button"
      onClick={copy}
      className={cn(
        'inline-flex items-center justify-center h-8 w-8 rounded-lg',
        'bg-white/10 hover:bg-white/15 border border-white/10',
        'text-white/70 hover:text-white',
        'opacity-0 group-hover:opacity-100 transition-all duration-200',
        'cursor-pointer'
      )}
      title="Copy code"
    >
      {copied ? <Check className="h-4 w-4 text-primary" /> : <Copy className="h-4 w-4" />}
    </button>
  );
}

function CopySkillContentButton({ text }: { text: string }) {
  const { copied, copy } = useCopyText(text);

  return (
    <Button
      type="button"
      variant="outline"
      size="icon"
      onClick={copy}
      disabled={!text}
      className="h-7 w-7 shrink-0 border-border/60 cursor-pointer"
      aria-label="Copy full skill content"
      title={copied ? 'Copied!' : 'Copy full skill content'}
    >
      {copied ? (
        <Check className="h-3.5 w-3.5 text-primary" />
      ) : (
        <Copy className="h-3.5 w-3.5 text-muted-foreground" />
      )}
    </Button>
  );
}

export function SkillViewer({ skill, content, isLoading }: SkillViewerProps) {
  if (!skill) {
    return (
      <ScrollArea className="h-full">
        <div className="flex min-h-full flex-col">
          <div className="flex flex-1 items-center justify-center min-h-[360px] p-8">
        <div className="text-center max-w-md animate-fade-in">
            <div className="relative w-20 h-20 mx-auto mb-6">
            <div className="absolute inset-0 rounded-2xl bg-primary/20 blur-xl" />
            <div className="relative flex h-full w-full items-center justify-center rounded-2xl border border-primary/20 bg-primary/10">
              <BookOpen className="h-9 w-9 text-primary" />
            </div>
          </div>
          <h2 className="text-lg font-semibold text-foreground mb-2">Select a skill</h2>
          <p className="text-sm text-muted-foreground leading-relaxed">
            Pick any skill from the catalog to read documentation, usage hints, and examples.
          </p>
            </div>
          </div>
          <Footer />
        </div>
      </ScrollArea>
    );
  }

  if (isLoading) {
    return (
      <ScrollArea className="h-full">
        <div className="flex min-h-full flex-col">
          <div className="flex flex-1 items-center justify-center min-h-[360px]">
        <div className="flex flex-col items-center gap-4">
          <div className="h-11 w-11 rounded-full border-2 border-primary/20 border-t-primary animate-spin" />
          <span className="text-sm text-muted-foreground font-mono">loading skill…</span>
            </div>
          </div>
          <Footer />
        </div>
      </ScrollArea>
    );
  }

  return (
    <ScrollArea className="h-full">
      <div className="preview-header shrink-0 border-b border-border/40 px-3 pb-2 pt-2 sm:px-4">
        <div className="flex items-start gap-2">
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
              <CategoryBadge category={skill.category} className="shrink-0" />

              {(skill.metadata.version || skill.metadata.author) && (
                <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground font-mono">
                  {skill.metadata.version && (
                    <span className="inline-flex items-center gap-0.5">
                      <Hash className="h-2.5 w-2.5" />
                      {skill.metadata.version}
                    </span>
                  )}
                  {skill.metadata.author && (
                    <span className="inline-flex max-w-[8rem] items-center gap-0.5 truncate">
                      <User className="h-2.5 w-2.5 shrink-0" />
                      {skill.metadata.author}
                    </span>
                  )}
                </div>
              )}
            </div>

            <h1 className="mt-1.5 text-sm font-semibold text-foreground leading-snug tracking-tight line-clamp-1 sm:text-base">
              {skill.name}
            </h1>

            <p className="mt-0.5 text-[11px] text-muted-foreground leading-snug line-clamp-1">
              {skill.description}
            </p>

            {(skill.keywords.length > 0 || skill.argumentHint) && (
              <div className="mt-1.5 flex flex-wrap items-center gap-1">
                {skill.keywords.slice(0, 4).map((keyword) => (
                  <span
                    key={keyword}
                    className="text-[10px] px-1.5 py-px rounded bg-muted/60 text-muted-foreground border border-border/50 font-mono"
                  >
                    {keyword}
                  </span>
                ))}
                {skill.keywords.length > 4 && (
                  <span className="text-[10px] text-muted-foreground">
                    +{skill.keywords.length - 4}
                  </span>
                )}
                {skill.argumentHint && (
                  <code className="inline-flex max-w-full items-center gap-1 truncate rounded border border-border/50 bg-muted/30 px-1.5 py-px text-[10px] font-mono text-foreground">
                    <Terminal className="h-2.5 w-2.5 shrink-0 text-primary" />
                    <span className="truncate">{skill.argumentHint}</span>
                  </code>
                )}
              </div>
            )}
          </div>

          <CopySkillContentButton text={content ?? ''} />
        </div>
      </div>

      <div className="px-3 py-2.5 sm:px-4 sm:py-3">
        <article className="prose prose-preview max-w-none">
          {content ? (
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              rehypePlugins={[
                rehypeHighlight,
                rehypeSlug,
                [rehypeAutolinkHeadings, { behavior: 'wrap' }],
              ]}
              components={{
                pre: ({ children, ...props }) => (
                  <div className="relative group my-3 code-block-wrapper">
                    <pre
                      {...props}
                      className="rounded-lg bg-[#0a0f1a] p-3 overflow-x-auto text-[12px] leading-relaxed border border-border/40"
                    >
                      {children}
                    </pre>
                    <div className="absolute top-2 right-2">
                      <CopyCodeButton text={String(children)} />
                    </div>
                  </div>
                ),
                a: ({ children, href, ...props }) => (
                  <a
                    href={href}
                    {...props}
                    className="text-primary hover:underline underline-offset-4 cursor-pointer"
                  >
                    {children}
                  </a>
                ),
                table: ({ children, ...props }) => (
                  <div className="my-3 overflow-x-auto rounded-lg border border-border/50 text-sm">
                    <table {...props} className="w-full">
                      {children}
                    </table>
                  </div>
                ),
                th: ({ children, ...props }) => (
                  <th
                    {...props}
                    className="text-left px-2.5 py-1.5 bg-muted/40 border-b border-border font-medium text-[10px] uppercase tracking-wider text-muted-foreground"
                  >
                    {children}
                  </th>
                ),
                td: ({ children, ...props }) => (
                  <td {...props} className="px-2.5 py-1.5 border-b border-border/30 text-[13px]">
                    {children}
                  </td>
                ),
                blockquote: ({ children, ...props }) => (
                  <blockquote
                    {...props}
                    className="my-3 border-l-2 border-primary bg-primary/5 rounded-r-md py-2 px-3 text-sm text-muted-foreground"
                  >
                    {children}
                  </blockquote>
                ),
              }}
            >
              {content}
            </ReactMarkdown>
          ) : (
            <p className="text-muted-foreground">No content available</p>
          )}
        </article>
      </div>
      <Footer />
    </ScrollArea>
  );
}
