'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  FileJson,
  ChevronDown,
  ChevronRight,
  Copy,
  Check,
  Globe,
} from 'lucide-react';
import { useSandbox } from './sandbox-context';

function getMethodColor(method: string): string {
  switch (method) {
    case 'GET': return 'bg-green-500/20 text-green-400 border-green-500/30';
    case 'POST': return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
    case 'PUT': return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';
    case 'PATCH': return 'bg-orange-500/20 text-orange-400 border-orange-500/30';
    case 'DELETE': return 'bg-red-500/20 text-red-400 border-red-500/30';
    default: return 'bg-gray-500/20 text-gray-400 border-gray-500/30';
  }
}

interface EndpointCardProps {
  endpoint: {
    method: string;
    path: string;
    description: string;
    requestSchema?: Record<string, string>;
    responseExample: unknown;
  };
}

function EndpointCard({ endpoint }: EndpointCardProps) {
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(JSON.stringify(endpoint.responseExample, null, 2));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="rounded-xl border border-white/10 overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center gap-3 p-4 bg-white/5 hover:bg-white/10 transition-colors"
      >
        <span className={`px-2 py-1 rounded text-xs font-mono font-bold border ${getMethodColor(endpoint.method)}`}>
          {endpoint.method}
        </span>
        <span className="font-mono text-sm text-white">{endpoint.path}</span>
        <span className="ml-auto text-gray-400">
          {expanded ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
        </span>
      </button>

      {expanded && (
        <motion.div
          initial={{ height: 0, opacity: 0 }}
          animate={{ height: 'auto', opacity: 1 }}
          exit={{ height: 0, opacity: 0 }}
          className="border-t border-white/10"
        >
          <div className="p-4 space-y-4">
            {/* Description */}
            <div>
              <h4 className="text-xs font-medium text-gray-400 uppercase mb-1">Description</h4>
              <p className="text-sm text-gray-300">{endpoint.description}</p>
            </div>

            {/* Request Schema */}
            {endpoint.requestSchema && Object.keys(endpoint.requestSchema).length > 0 && (
              <div>
                <h4 className="text-xs font-medium text-gray-400 uppercase mb-2">Request Schema</h4>
                <div className="bg-gray-900 rounded-lg p-3">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="text-gray-500 text-left">
                        <th className="pb-2">Field</th>
                        <th className="pb-2">Type</th>
                      </tr>
                    </thead>
                    <tbody>
                      {Object.entries(endpoint.requestSchema).map(([field, type]) => (
                        <tr key={field} className="border-t border-white/5">
                          <td className="py-2 font-mono text-brand">{field}</td>
                          <td className="py-2 text-gray-400">{type}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Response Example */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-xs font-medium text-gray-400 uppercase">Response Example</h4>
                <button
                  onClick={handleCopy}
                  className="flex items-center gap-1 text-xs text-gray-400 hover:text-white transition-colors"
                >
                  {copied ? (
                    <><Check className="w-3 h-3 text-green-400" /> Copied!</>
                  ) : (
                    <><Copy className="w-3 h-3" /> Copy</>
                  )}
                </button>
              </div>
              <pre className="bg-gray-900 rounded-lg p-3 overflow-x-auto text-xs">
                <code className="text-gray-300">
                  {JSON.stringify(endpoint.responseExample, null, 2)}
                </code>
              </pre>
            </div>
          </div>
        </motion.div>
      )}
    </div>
  );
}

export function ApiDocsPanel() {
  const { sandbox } = useSandbox();
  const apiDocs = sandbox?.getApiDocs();

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-3 border-b border-white/10">
        <FileJson className="w-5 h-5 text-brand" />
        <h3 className="font-semibold text-white">API Documentation</h3>
        {apiDocs?.endpoints.length && (
          <span className="text-xs bg-brand-secondary/20 text-brand-secondary-light px-2 py-0.5 rounded-full">
            {apiDocs.endpoints.length} endpoints
          </span>
        )}
      </div>

      {/* Endpoints */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {!apiDocs || apiDocs.endpoints.length === 0 ? (
          <div className="text-center py-12 text-gray-500">
            <Globe className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p>No API stubs defined</p>
            <p className="text-sm mt-1">Add API stubs to the sandbox config</p>
          </div>
        ) : (
          apiDocs.endpoints.map((endpoint, i) => (
            <EndpointCard key={`${endpoint.method}-${endpoint.path}-${i}`} endpoint={endpoint} />
          ))
        )}
      </div>
    </div>
  );
}
