import React, { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { RefreshCw, Copy, Check } from 'lucide-react';
import { cn } from '@/lib/utils';

const VARIABLE_GROUPS = {
  typography: [
    { name: '--text-body', label: 'Body Size', min: 0.75, max: 1.5, step: 0.0125, unit: 'rem' },
    { name: '--text-label', label: 'Label Size', min: 0.75, max: 1.25, step: 0.0125, unit: 'rem' },
    { name: '--text-caption', label: 'Caption Size', min: 0.625, max: 1.125, step: 0.0125, unit: 'rem' },
    { name: '--text-table', label: 'Table Text Size', min: 0.75, max: 1.25, step: 0.0125, unit: 'rem' },
    { name: '--text-subtitle', label: 'Subtitle Size', min: 1, max: 2, step: 0.0125, unit: 'rem' },
    { name: '--text-title', label: 'Title Size', min: 1.25, max: 3, step: 0.0125, unit: 'rem' },
    { name: '--text-title-lg', label: 'Large Title Size', min: 1.5, max: 4, step: 0.0125, unit: 'rem' },
  ],
  spacing: [
    { name: '--radius', label: 'Global Radius', min: 0, max: 2, step: 0.1, unit: 'rem' },
  ]
};

const ThemeTuner = ({ theme }) => {
  const [values, setValues] = useState({});
  const [copied, setCopied] = useState(false);
  const [activeTab, setActiveTab] = useState('typography');

  // Load initial values from computed styles
  useEffect(() => {
    const computed = getComputedStyle(document.documentElement);
    const initial = {};
    
    [...VARIABLE_GROUPS.typography, ...VARIABLE_GROUPS.spacing].forEach(v => {
      const val = computed.getPropertyValue(v.name).trim();
      // Try to parse clean generic value if possible, else default to mid
      if (val.includes('clamp')) {
         // simplified parsing for clamp (just taking a guess or leaving as is? 
         // For the tuner we actully want to OVERRIDE clamp with fixed rem for simplicity or parse the middle value)
         // For now, let's start with a safe default if it's complex
         initial[v.name] = v.name.includes('title') ? 1.5 : 1;
      } else if (val.endsWith('rem')) {
        initial[v.name] = parseFloat(val);
      } else if (val.endsWith('px')) {
        initial[v.name] = parseFloat(val) / 16;
      } else {
        initial[v.name] = (v.min + v.max) / 2; 
      }
    });
    setValues(initial);
  }, []);

  const handleUpdate = (name, val) => {
    setValues(prev => ({ ...prev, [name]: val }));
    document.documentElement.style.setProperty(name, `${val}rem`);
  };

  const handleReset = () => {
    [...VARIABLE_GROUPS.typography, ...VARIABLE_GROUPS.spacing].forEach(v => {
      document.documentElement.style.removeProperty(v.name);
    });
    // Re-trigger load or just manually set back? 
    // Ideally we reload from stylesheet, but for now let's just clear inline styles
    const computed = getComputedStyle(document.documentElement);
    // ... logic to reload would go here
  };

  const generateCSS = () => {
    return `:root {
  ${Object.entries(values).map(([k, v]) => `${k}: ${v}rem;`).join('\n  ')}
}`;
  };

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

  return (
    <div className={cn("grid grid-cols-1 lg:grid-cols-3 gap-6", theme === 'dark' ? "text-slate-200" : "text-slate-700")}>
      
      {/* Controls Panel */}
      <Card className={cn("lg:col-span-1 p-6 border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-white border-slate-200")}>
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-title font-title text-foreground">Ajustes de Tema</h3>
          <Button variant="ghost" size="icon" onClick={handleReset} title="Resetar para o padrão">
            <RefreshCw size={16} />
          </Button>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="w-full mb-6 grid grid-cols-2">
            <TabsTrigger value="typography">Tipografia</TabsTrigger>
            <TabsTrigger value="spacing">Espaçamento</TabsTrigger>
          </TabsList>

          <TabsContent value="typography" className="space-y-6">
            {VARIABLE_GROUPS.typography.map((variable) => (
              <div key={variable.name} className="space-y-3">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">{variable.label}</label>
                  <span className="font-mono text-xs bg-muted px-2 py-1 rounded">{values[variable.name]?.toFixed(3)}{variable.unit}</span>
                </div>
                <Slider 
                  value={[values[variable.name] || 0]} 
                  min={variable.min} 
                  max={variable.max} 
                  step={variable.step}
                  onValueChange={([val]) => handleUpdate(variable.name, val)}
                  className="[&>.relative>.absolute]:bg-emerald-500"
                />
              </div>
            ))}
          </TabsContent>

          <TabsContent value="spacing" className="space-y-6">
            {VARIABLE_GROUPS.spacing.map((variable) => (
              <div key={variable.name} className="space-y-3">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">{variable.label}</label>
                  <span className="font-mono text-xs bg-muted px-2 py-1 rounded">{values[variable.name]?.toFixed(3)}{variable.unit}</span>
                </div>
                 <Slider 
                  value={[values[variable.name] || 0]} 
                  min={variable.min} 
                  max={variable.max} 
                  step={variable.step}
                  onValueChange={([val]) => handleUpdate(variable.name, val)}
                  className="[&>.relative>.absolute]:bg-emerald-500"
                />
              </div>
            ))}
          </TabsContent>
        </Tabs>

        <div className="mt-8 pt-6 border-t border-border">
          <Button className="w-full gap-2" variant="outline" onClick={copyToClipboard}>
            {copied ? <Check size={16} className="text-emerald-500" /> : <Copy size={16} />}
            {copied ? 'Copiado!' : 'Copiar CSS'}
          </Button>
        </div>
      </Card>

      {/* Preview Panel */}
      <div className="lg:col-span-2 space-y-6">
        <Card className={cn("p-8 border min-h-[500px]", theme === 'dark' ? "bg-[#0f0f0f] border-white/10" : "bg-white border-slate-200")}>
           <div className="mb-8">
             <span className="text-label font-label text-emerald-500 mb-2 block">Preview Real-time</span>
             <h1 className="text-title font-title text-foreground mb-4">Título Principal (H1)</h1>
             <p className="text-subtitle font-body text-muted-foreground mb-6">Subtítulo que acompanha o título principal e dá contexto.</p>
             
             <div className="prose dark:prose-invert max-w-none">
               <p className="text-body font-body text-foreground mb-4">
                 Este é um parágrafo de corpo de texto (body). O ajuste da variável <code className="text-xs bg-muted px-1 rounded">--text-body</code> afeta diretamente a legibilidade.
                 A intenção é garantir que o usuário tenha uma leitura confortável.
               </p>
               <p className="text-body font-body text-foreground mb-8">
                 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
               </p>
             </div>

             <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
                <div className={cn("p-4 rounded-xl border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-50 border-slate-200")}>
                   <span className="text-caption text-muted-foreground mb-1 block">KPI Label</span>
                   <span className="text-title-lg font-title text-foreground block">R$ 14.230,00</span>
                </div>
                <div className={cn("p-4 rounded-xl border", theme === 'dark' ? "bg-white/5 border-white/10" : "bg-slate-50 border-slate-200")}>
                   <span className="text-caption text-muted-foreground mb-1 block">Status</span>
                   <div className="flex gap-2">
                      <span className="text-label font-label px-2 py-1 rounded bg-emerald-500/20 text-emerald-600">Ativo</span>
                      <span className="text-label font-label px-2 py-1 rounded bg-blue-500/20 text-blue-600">Em dia</span>
                   </div>
                </div>
             </div>

             <div>
                <span className="text-label font-label mb-2 block text-muted-foreground">Tabela de Exemplo</span>
                <div className={cn("rounded-lg border overflow-hidden", theme === 'dark' ? "border-white/10" : "border-slate-200")}>
                  <table className="w-full text-left text-table font-body">
                    <thead className={cn("bg-muted", theme === 'dark' ? "bg-white/5" : "bg-slate-50")}>
                      <tr>
                        <th className="p-3 font-label text-muted-foreground">Nome</th>
                        <th className="p-3 font-label text-muted-foreground">Status</th>
                        <th className="p-3 font-label text-muted-foreground">Valor</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      <tr>
                        <td className="p-3">João Silva</td>
                        <td className="p-3">Ativo</td>
                        <td className="p-3">R$ 1.200</td>
                      </tr>
                      <tr>
                         <td className="p-3">Maria Santos</td>
                        <td className="p-3">Pendente</td>
                        <td className="p-3">R$ 3.450</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
             </div>
           </div>
        </Card>
      </div>
    </div>
  );
};

export default ThemeTuner;
