"use client";

import { Fragment, useState } from "react";
import { Dialog, Transition, Tab } from "@headlessui/react";
import {
  XMarkIcon,
  ClipboardIcon,
  CheckIcon,
} from "@heroicons/react/24/outline";

interface DocumentationModalProps {
  isOpen: boolean;
  onClose: () => void;
}

function CodeBlock({ code, language }: { code: string; language: string }) {
  const [copied, setCopied] = useState(false);

  const copyToClipboard = () => {
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="relative group rounded-lg bg-slate-900 p-4 font-mono text-sm text-slate-50 overflow-x-auto">
      <button
        onClick={copyToClipboard}
        className="absolute right-2 top-2 p-1.5 rounded-md bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700 opacity-0 group-hover:opacity-100 transition-all"
        title="Copy code"
      >
        {copied ? (
          <CheckIcon className="w-4 h-4" />
        ) : (
          <ClipboardIcon className="w-4 h-4" />
        )}
      </button>
      <pre className="whitespace-pre text-xs md:text-sm leading-relaxed">
        <code className={`language-${language}`}>{code}</code>
      </pre>
    </div>
  );
}

export default function DocumentationModal({
  isOpen,
  onClose,
}: DocumentationModalProps) {
  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-[100]" onClose={onClose}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4 text-center">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-4xl transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all dark:bg-slate-900">
                <div className="flex items-center justify-between mb-6 border-b border-slate-200 dark:border-slate-800 pb-4">
                  <div>
                    <Dialog.Title
                      as="h3"
                      className="text-2xl font-bold leading-6 text-gray-900 dark:text-white"
                    >
                      Introduction
                    </Dialog.Title>
                    <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                      Explore the ElevenLabs API reference with comprehensive
                      guides, code examples, and endpoint documentation
                    </p>
                  </div>
                  <button
                    onClick={onClose}
                    className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-slate-800 dark:hover:text-gray-300 transition-colors"
                  >
                    <XMarkIcon className="h-6 w-6" />
                  </button>
                </div>

                <div className="mt-4 space-y-8 text-left">
                  {/* Installation Section */}
                  <section className="space-y-4">
                    <h4 className="text-xl font-bold text-gray-900 dark:text-white border-b pb-2 border-gray-100 dark:border-gray-800">
                      Installation
                    </h4>
                    <p className="text-gray-600 dark:text-gray-300">
                      You can interact with the API through HTTP or Websocket
                      requests from any language, via our official Python
                      bindings or our official Node.js libraries.
                    </p>

                    <div className="space-y-4">
                      <div>
                        <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          To install the official Python bindings, run the
                          following command:
                        </p>
                        <CodeBlock
                          language="bash"
                          code="pip install elevenlabs"
                        />
                      </div>

                      <div>
                        <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          To install the official Node.js library, run the
                          following command in your Node.js project directory:
                        </p>
                        <CodeBlock
                          language="bash"
                          code="npm install @elevenlabs/elevenlabs-js"
                        />
                      </div>
                    </div>
                  </section>

                  {/* Tracking Costs Section */}
                  <section className="space-y-4">
                    <h4 className="text-xl font-bold text-gray-900 dark:text-white border-b pb-2 border-gray-100 dark:border-gray-800">
                      Tracking generation costs
                    </h4>
                    <p className="text-gray-600 dark:text-gray-300">
                      Access response headers to retrieve generation metadata
                      including character costs.
                    </p>

                    <Tab.Group>
                      <Tab.List className="flex space-x-1 rounded-xl bg-slate-100 p-1 dark:bg-slate-800/50">
                        {["Python", "JavaScript"].map((category) => (
                          <Tab
                            key={category}
                            className={({ selected }) =>
                              `w-full rounded-lg py-2.5 text-sm font-medium leading-5 transition-all
                               ${
                                 selected
                                   ? "bg-white text-brand-green shadow dark:bg-slate-700 dark:text-white"
                                   : "text-gray-600 hover:bg-white/[0.12] hover:text-brand-green dark:text-gray-400"
                               }`
                            }
                          >
                            {category}
                          </Tab>
                        ))}
                      </Tab.List>
                      <Tab.Panels className="mt-2">
                        <Tab.Panel>
                          <CodeBlock
                            language="python"
                            code={`from elevenlabs.client import ElevenLabs

client = ElevenLabs(api_key="your_api_key")

# Get raw response with headers
response = client.text_to_speech.with_raw_response.convert(
    text="Hello, world!",
    voice_id="voice_id"
)

# Access character cost from headers
char_cost = response.headers.get("x-character-count")
audio_data = response.data`}
                          />
                        </Tab.Panel>
                        <Tab.Panel>
                          <CodeBlock
                            language="typescript"
                            code={`import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';

const client = new ElevenLabsClient({ apiKey: 'your_api_key' });

// Get raw response with headers
const { data, rawResponse } = await client.textToSpeech
  .convert('voice_id', {
    text: 'Hello, world!',
    modelId: 'eleven_multilingual_v2',
  })
  .withRawResponse();

// Access character cost from headers
const charCost = rawResponse.headers.get('x-character-count');
const requestId = rawResponse.headers.get('request-id');
const audioData = data;`}
                          />
                        </Tab.Panel>
                      </Tab.Panels>
                    </Tab.Group>

                    <div className="bg-blue-50 dark:bg-blue-900/20 rounded-xl p-4 text-sm text-blue-800 dark:text-blue-200">
                      <p className="font-semibold mb-2">
                        The raw response provides access to:
                      </p>
                      <ul className="list-disc list-inside space-y-1 ml-2">
                        <li>Response data - The actual API response content</li>
                        <li>
                          HTTP headers - Metadata including character costs and
                          request IDs
                        </li>
                      </ul>
                    </div>

                    {/* Waveform Placeholder */}
                    <div className="mt-6 h-32 w-full bg-slate-100 dark:bg-slate-800 rounded-xl flex items-center justify-center border-2 border-dashed border-slate-300 dark:border-slate-700">
                      <div className="text-center text-slate-400">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                          strokeWidth={1.5}
                          stroke="currentColor"
                          className="w-8 h-8 mx-auto mb-2"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z"
                          />
                        </svg>
                        <span className="text-sm font-medium">
                          ElevenLabs Waveform Visualization
                        </span>
                      </div>
                    </div>
                  </section>
                </div>

                <div className="mt-8 flex justify-end">
                  <button
                    type="button"
                    className="inline-flex justify-center rounded-xl border border-transparent bg-slate-100 px-6 py-3 text-sm font-medium text-slate-900 hover:bg-slate-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-slate-500 focus-visible:ring-offset-2 dark:bg-slate-800 dark:text-slate-100 dark:hover:bg-slate-700"
                    onClick={onClose}
                  >
                    Close Documentation
                  </button>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}
