"use client";
import React, { useEffect, useState } from "react";
import { cn } from "../shared/utils";

// Custom Button component to replace @/components/ui/button
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: "ghost" | "outline";
  size?: "sm" | "icon";
  children: React.ReactNode;
}

const Button = ({ 
  variant = "outline", 
  size = "sm", 
  className, 
  children, 
  ...props 
}: ButtonProps) => {
  const baseClasses = "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background";
  
  const variantClasses = {
    ghost: "hover:bg-accent hover:text-accent-foreground",
    outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground"
  };
  
  const sizeClasses = {
    sm: "h-8 px-3 py-2",
    icon: "h-10 w-10"
  };
  
  return (
    <button
      className={cn(baseClasses, variantClasses[variant], sizeClasses[size], className)}
      {...props}
    >
      {children}
    </button>
  );
};

// Custom icons to replace lucide-react
const CheckIcon = ({ className }: { className?: string }) => (
  <svg
    className={className}
    fill="none"
    height="16"
    width="16"
    viewBox="0 0 24 24"
    stroke="currentColor"
    strokeWidth="2"
  >
    <polyline points="20,6 9,17 4,12" />
  </svg>
);

const CopyIcon = ({ className }: { className?: string }) => (
  <svg
    className={className}
    fill="none"
    height="16"
    width="16"
    viewBox="0 0 24 24"
    stroke="currentColor"
    strokeWidth="2"
  >
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
  </svg>
);

// Custom motion div to replace motion.div
const MotionDiv = ({ 
  children, 
  className, 
  layoutId, 
  initial, 
  transition,
  ...props 
}: {
  children?: React.ReactNode;
  className?: string;
  layoutId?: string;
  initial?: boolean;
  transition?: any;
  [key: string]: any;
}) => {
  return (
    <div 
      className={className}
      style={{
        transition: `all ${transition?.type === 'spring' ? '0.3s' : '0.2s'} ease-out`
      }}
      {...props}
    >
      {children}
    </div>
  );
};

// Custom theme hook to replace next-themes
const useTheme = () => {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  
  useEffect(() => {
    // Check if user prefers dark mode
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    setTheme(mediaQuery.matches ? 'dark' : 'light');
    
    const handleChange = (e: MediaQueryListEvent) => {
      setTheme(e.matches ? 'dark' : 'light');
    };
    
    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);
  
  return { theme };
};

// Custom code highlighting function to replace shiki
const highlightCode = (code: string, isDark: boolean) => {
  // Simple syntax highlighting for common languages
  const keywords = ['npm', 'yarn', 'pnpm', 'bun', 'install', 'add', 'remove', 'dev', 'global'];
  const strings = /"[^"]*"/g;
  const comments = /\/\/.*$/gm;
  
  let highlighted = code
    .replace(strings, '<span style="color: #ce9178;">$&</span>')
    .replace(comments, '<span style="color: #6a9955;">$&</span>');
  
  keywords.forEach(keyword => {
    const regex = new RegExp(`\\b${keyword}\\b`, 'g');
    highlighted = highlighted.replace(regex, `<span style="color: #569cd6;">${keyword}</span>`);
  });
  
  const bgColor = isDark ? '#1e1e1e' : '#ffffff';
  const textColor = isDark ? '#d4d4d4' : '#1e1e1e';
  
  return `<pre style="background-color: ${bgColor}; color: ${textColor}; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;">${highlighted}</pre>`;
};

interface ScriptCopyBtnProps extends React.HTMLAttributes<HTMLDivElement> {
  showMultiplePackageOptions?: boolean;
  commandMap: Record<string, string>;
  className?: string;
}

export function ScriptCopyBtn({
  showMultiplePackageOptions = true,
  commandMap,
  className,
}: ScriptCopyBtnProps) {
  const packageManagers = Object.keys(commandMap);
  const [packageManager, setPackageManager] = useState(packageManagers[0]);
  const [copied, setCopied] = useState(false);
  const [highlightedCode, setHighlightedCode] = useState("");
  const { theme } = useTheme();
  const command = commandMap[packageManager];

  useEffect(() => {
    // Use custom highlighting instead of shiki
    const highlighted = highlightCode(command, theme === 'dark');
    setHighlightedCode(highlighted);
  }, [command, theme]);

  const copyToClipboard = () => {
    navigator.clipboard.writeText(command);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div
      className={cn(
        "mx-auto flex max-w-md items-center justify-center",
        className,
      )}
    >
      <div className="w-full space-y-2">
        <div className="mb-2 flex items-center justify-between">
          {showMultiplePackageOptions && (
            <div className="relative">
              <div className="inline-flex overflow-hidden rounded-md border border-gray-200 dark:border-gray-700 text-xs">
                {packageManagers.map((pm, index) => (
                  <div key={pm} className="flex items-center">
                    {index > 0 && (
                      <div className="h-4 w-px bg-gray-200 dark:bg-gray-700" aria-hidden="true" />
                    )}
                    <Button
                      variant="ghost"
                      size="sm"
                      className={`relative rounded-none bg-white dark:bg-gray-900 px-2 py-1 hover:bg-gray-100 dark:hover:bg-gray-800 ${
                        packageManager === pm
                          ? "text-blue-600 dark:text-blue-400"
                          : "text-gray-600 dark:text-gray-400"
                      }`}
                      onClick={() => setPackageManager(pm)}
                    >
                      {pm}
                      {packageManager === pm && (
                        <MotionDiv
                          className="absolute inset-x-0 bottom-[1px] mx-auto h-0.5 w-[90%] bg-blue-600 dark:bg-blue-400"
                          layoutId="activeTab"
                          initial={false}
                          transition={{
                            type: "spring",
                            stiffness: 500,
                            damping: 30,
                          }}
                        >
                          {/* Empty children for the underline indicator */}
                        </MotionDiv>
                      )}
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="relative flex items-center">
          <div className="min-w-[300px] grow font-mono">
            {highlightedCode ? (
              <div
                className={`[&>pre]:overflow-x-auto [&>pre]:rounded-md [&>pre]:p-2 [&>pre]:px-4 [&>pre]:font-mono ${
                  theme === "dark" ? "dark" : "light"
                }`}
                dangerouslySetInnerHTML={{ __html: highlightedCode }}
              />
            ) : (
              <pre className="rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-2 px-4 font-mono text-gray-900 dark:text-gray-100">
                {command}
              </pre>
            )}
          </div>
          <Button
            variant="outline"
            size="icon"
            className="relative ml-2 rounded-md border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 hover:bg-gray-100 dark:hover:bg-gray-800"
            onClick={copyToClipboard}
            aria-label={copied ? "Copied" : "Copy to clipboard"}
          >
            <span className="sr-only">{copied ? "Copied" : "Copy"}</span>
            <CopyIcon
              className={`h-4 w-4 transition-all duration-300 ${
                copied ? "scale-0" : "scale-100"
              }`}
            />
            <CheckIcon
              className={`absolute inset-0 m-auto h-4 w-4 transition-all duration-300 ${
                copied ? "scale-100" : "scale-0"
              }`}
            />
          </Button>
        </div>
      </div>
    </div>
  );
}
