'use client';

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

const diagramTypes = [
  { value: 'flowchart', label: 'Flowchart' },
  { value: 'sequence', label: 'Sequence Diagram' },
  { value: 'class', label: 'Class Diagram' },
  { value: 'state', label: 'State Diagram' },
  { value: 'er', label: 'Entity Relationship' },
  { value: 'journey', label: 'User Journey' },
  { value: 'gantt', label: 'Gantt Chart' },
  { value: 'pie', label: 'Pie Chart' },
  { value: 'mindmap', label: 'Mind Map' },
  { value: 'timeline', label: 'Timeline' },
  { value: 'gitgraph', label: 'Git Graph' },
];

const styles = [
  { value: 'simple', label: 'Simple' },
  { value: 'detailed', label: 'Detailed' },
  { value: 'complex', label: 'Complex' },
];

export default function MermaidGeneratorPage() {
  const [description, setDescription] = useState('');
  const [diagramType, setDiagramType] = useState('flowchart');
  const [style, setStyle] = useState('detailed');
  const [render, setRender] = useState(true);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);

  const handleGenerate = async () => {
    if (!description.trim()) {
      toast.error('Please enter a description');
      return;
    }

    setLoading(true);
    setResult(null);

    try {
      const response = await modulesApi.generateMermaid({
        description,
        diagram_type: diagramType,
        style,
        render,
      });

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

  const handleCopyCode = () => {
    if (result?.code) {
      navigator.clipboard.writeText(result.code);
      toast.success('Code copied to clipboard!');
    }
  };

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

    const blob = new Blob([result.code], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `diagram-${diagramType}.mmd`;
    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">
          <Network className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Mermaid Diagram Generator</h1>
          <p className="text-gray-500">Generate diagram code from natural language</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">
              Description
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Describe the diagram you want to create... e.g., 'A flowchart showing user authentication process with login, password validation, and session creation'"
              className="input-field min-h-[150px] resize-none"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Diagram Type
              </label>
              <select
                value={diagramType}
                onChange={(e) => setDiagramType(e.target.value)}
                className="select-field"
              >
                {diagramTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Style
              </label>
              <select
                value={style}
                onChange={(e) => setStyle(e.target.value)}
                className="select-field"
              >
                {styles.map((s) => (
                  <option key={s.value} value={s.value}>
                    {s.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={render}
              onChange={(e) => setRender(e.target.checked)}
              className="rounded border-gray-700 bg-forge-dark text-forge-yellow focus:ring-forge-yellow"
            />
            <label className="text-sm text-gray-300">
              Auto-render diagram preview
            </label>
          </div>

          <button
            onClick={handleGenerate}
            disabled={loading || !description.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 ? 'Generating...' : 'Generate Diagram'}
          </button>
        </div>

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

          {result?.code ? (
            <>
              <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">Mermaid Code</span>
                  <div className="flex gap-2">
                    <button
                      onClick={handleCopyCode}
                      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">
                  <code>{result.code}</code>
                </pre>
              </div>

              {result.rendered?.image_url && (
                <div className="bg-forge-dark rounded-lg p-4 border border-gray-800">
                  <p className="text-xs text-gray-500 mb-2">Preview</p>
                  <img
                    src={result.rendered.image_url}
                    alt="Diagram preview"
                    className="w-full"
                  />
                </div>
              )}
            </>
          ) : (
            <div className="bg-forge-dark rounded-lg border border-gray-800 p-12 flex items-center justify-center">
              <p className="text-gray-500">Generated diagram will appear here</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
