'use client';

import { useState, useRef } from 'react';
import { toast } from 'react-hot-toast';
import { Image as ImageIcon, Download, Sparkles, Upload, FileCode } from 'lucide-react';
import { modulesApi } from '@/lib/api';

const themes = [
  { value: 'default', label: 'Default' },
  { value: 'dark', label: 'Dark' },
  { value: 'forest', label: 'Forest' },
  { value: 'neutral', label: 'Neutral' },
  { value: 'forge', label: 'Forge (Yellow/White)' },
];

const formats = [
  { value: 'svg', label: 'SVG' },
  { value: 'png', label: 'PNG' },
];

const backgrounds = [
  { value: 'transparent', label: 'Transparent' },
  { value: 'white', label: 'White' },
  { value: 'black', label: 'Black' },
];

export default function MermaidRendererPage() {
  const [code, setCode] = useState('');
  const [theme, setTheme] = useState('default');
  const [outputFormat, setOutputFormat] = useState('svg');
  const [background, setBackground] = useState('transparent');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleRender = async () => {
    if (!code.trim()) {
      toast.error('Please enter Mermaid code');
      return;
    }

    setLoading(true);
    setResult(null);

    try {
      const response = await modulesApi.renderMermaid({
        code,
        output_format: outputFormat,
        theme,
        background,
      });

      setResult(response.data);
      toast.success('Diagram rendered!');
    } catch (err: any) {
      toast.error(err.response?.data?.detail || 'Failed to render diagram');
    } finally {
      setLoading(false);
    }
  };

  const handleDownloadImage = () => {
    if (!result?.image_url) return;

    const a = document.createElement('a');
    a.href = result.image_url;
    a.download = `diagram.${outputFormat}`;
    a.click();
    toast.success('Downloaded!');
  };

  const handleExportCode = () => {
    if (!code.trim()) return;
    const blob = new Blob([code], { type: 'text/vnd.mermaid' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'diagram.mmd';
    a.click();
    window.URL.revokeObjectURL(url);
    toast.success('Code exported!');
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target?.result as string;
      setCode(content);
      toast.success('Diagram code imported!');
    };
    reader.readAsText(file);
    // Reset input so same file can be selected again
    e.target.value = '';
  };

  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">
          <ImageIcon className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Mermaid Diagram Renderer</h1>
          <p className="text-gray-500">Render Mermaid code to images</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Controls */}
        <div className="space-y-6">
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-medium text-gray-300">
                Mermaid Code
              </label>
              <div className="flex gap-2">
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleFileChange}
                  accept=".mmd,.txt"
                  className="hidden"
                />
                <button
                  onClick={handleImportClick}
                  className="text-xs flex items-center gap-1 text-forge-yellow hover:text-white transition-colors"
                  title="Import .mmd file"
                >
                  <Upload className="w-3 h-3" /> Import
                </button>
                <button
                  onClick={handleExportCode}
                  className="text-xs flex items-center gap-1 text-forge-yellow hover:text-white transition-colors"
                  title="Export code to .mmd"
                >
                  <FileCode className="w-3 h-3" /> Export
                </button>
              </div>
            </div>
            <textarea
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder={`graph TD\n  A[Start] --> B[Process]\n  B --> C[End]`}
              className="input-field min-h-[200px] resize-none font-mono text-sm"
            />
          </div>

          <div className="grid grid-cols-3 gap-4">
            <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>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Format
              </label>
              <select
                value={outputFormat}
                onChange={(e) => setOutputFormat(e.target.value)}
                className="select-field"
              >
                {formats.map((f) => (
                  <option key={f.value} value={f.value}>
                    {f.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Background
              </label>
              <select
                value={background}
                onChange={(e) => setBackground(e.target.value)}
                className="select-field"
              >
                {backgrounds.map((b) => (
                  <option key={b.value} value={b.value}>
                    {b.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <button
            onClick={handleRender}
            disabled={loading || !code.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 ? 'Rendering...' : 'Render Diagram'}
          </button>
        </div>

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

          {result?.image_url ? (
            <>
              <div className="bg-forge-dark rounded-lg p-4 border border-gray-800">
                <img
                  src={result.image_url}
                  alt="Rendered diagram"
                  className="w-full"
                />
              </div>
              <button
                onClick={handleDownloadImage}
                className="btn-primary w-full flex items-center justify-center gap-2"
              >
                <Download className="w-4 h-4" />
                Download Image
              </button>
            </>
          ) : (
            <div className="bg-forge-dark rounded-lg border border-gray-800 p-12 flex items-center justify-center">
              <p className="text-gray-500">Rendered diagram will appear here</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
