'use client';

import { useState } from 'react';
import { toast } from 'react-hot-toast';
import { FileText, Download, Sparkles, Copy } from 'lucide-react';
import { modulesApi } from '@/lib/api';

const outputFormats = [
  { value: 'html', label: 'HTML' },
  { value: 'plain', label: 'Plain Text' },
];

const themes = [
  { value: 'github', label: 'GitHub' },
  { value: 'default', label: 'Default' },
];

export default function MarkdownConverterPage() {
  const [content, setContent] = useState('');
  const [outputFormat, setOutputFormat] = useState('html');
  const [theme, setTheme] = useState('github');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);

  const handleConvert = async () => {
    if (!content.trim()) {
      toast.error('Please enter Markdown content');
      return;
    }

    setLoading(true);
    setResult(null);

    try {
      const response = await modulesApi.convertMarkdown({
        content,
        output_format: outputFormat,
        theme: outputFormat === 'html' ? theme : undefined,
      });

      setResult(response.data);
      toast.success('Markdown converted!');
    } catch (err: any) {
      toast.error(err.response?.data?.detail || 'Failed to convert markdown');
    } finally {
      setLoading(false);
    }
  };

  const handleCopy = () => {
    if (result?.output) {
      navigator.clipboard.writeText(result.output);
      toast.success('Copied to clipboard!');
    }
  };

  const handleDownload = () => {
    if (!result?.output) return;

    const blob = new Blob([result.output], {
      type: outputFormat === 'html' ? 'text/html' : 'text/plain',
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `converted.${outputFormat === 'html' ? 'html' : 'txt'}`;
    a.click();
    window.URL.revokeObjectURL(url);
    toast.success('Downloaded!');
  };

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      <div className="flex items-center gap-4">
        <div className="w-12 h-12 bg-forge-yellow/10 rounded-lg flex items-center justify-center">
          <FileText className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Markdown Converter</h1>
          <p className="text-gray-500">Convert Markdown to HTML or plain text</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Controls */}
        <div className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Markdown Content
            </label>
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="# Hello World&#10;&#10;This is **bold** and this is *italic*.&#10;&#10;- List item 1&#10;- List item 2"
              className="input-field min-h-[300px] resize-none font-mono text-sm"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Output Format
              </label>
              <select
                value={outputFormat}
                onChange={(e) => setOutputFormat(e.target.value)}
                className="select-field"
              >
                {outputFormats.map((f) => (
                  <option key={f.value} value={f.value}>
                    {f.label}
                  </option>
                ))}
              </select>
            </div>
            {outputFormat === 'html' && (
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Theme
                </label>
                <select
                  value={theme}
                  onChange={(e) => setTheme(e.target.value)}
                  className="select-field"
                >
                  {themes.map((t) => (
                    <option key={t.value} value={t.value}>
                      {t.label}
                    </option>
                  ))}
                </select>
              </div>
            )}
          </div>

          <button
            onClick={handleConvert}
            disabled={loading || !content.trim()}
            className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Sparkles className="w-5 h-5" />
            {loading ? 'Converting...' : 'Convert'}
          </button>
        </div>

        {/* Results */}
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-white">Converted Output</h2>

          {result?.output ? (
            <>
              <div className="bg-forge-dark rounded-lg p-4 border border-gray-800">
                <div className="flex justify-between items-center mb-2">
                  <span className="text-xs text-gray-500 font-mono">
                    {outputFormat === 'html' ? 'HTML Output' : 'Plain Text'}
                  </span>
                  <div className="flex gap-2">
                    <button
                      onClick={handleCopy}
                      className="text-xs text-forge-yellow hover:text-forge-yellow/80 flex items-center gap-1"
                    >
                      <Copy className="w-3 h-3" />
                      Copy
                    </button>
                    <button
                      onClick={handleDownload}
                      className="text-xs text-forge-yellow hover:text-forge-yellow/80 flex items-center gap-1"
                    >
                      <Download className="w-3 h-3" />
                      Download
                    </button>
                  </div>
                </div>
                <pre className="text-sm text-gray-300 overflow-x-auto max-h-[400px]">
                  <code>{result.output}</code>
                </pre>
              </div>

              {outputFormat === 'html' && (
                <div className="bg-forge-dark rounded-lg p-4 border border-gray-800">
                  <p className="text-xs text-gray-500 mb-2">Preview</p>
                  <div
                    className="prose prose-invert max-w-none"
                    dangerouslySetInnerHTML={{ __html: result.output }}
                  />
                </div>
              )}
            </>
          ) : (
            <div className="bg-forge-dark rounded-lg border border-gray-800 p-12 flex items-center justify-center">
              <p className="text-gray-500">Converted output will appear here</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
