'use client'

import { useState } from 'react'
import Link from 'next/link'
import { generateWorkout, type WorkoutGenerationParams } from '@/actions/workout'

export interface AIWorkoutResult {
  titulo?: string;
  title?: string;
  descricao?: string;
  description?: string;
  duracao_minutos?: number;
  duration?: number;
  foco?: string;
  conteudo_json?: { title: string; type: string; reps: string | number }[];
  exercises?: { title: string; type: string; reps: string | number }[];
}

export default function AIGeneratorPage() {
  const [params, setParams] = useState<WorkoutGenerationParams>({
    focus: 'Emagrecimento',
    limitation: '',
    duration: 30,
    intensity: 'Leve',
    environment: 'Casa',
  })
  
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<AIWorkoutResult | null>(null)

  const handleGenerate = async () => {
    setLoading(true)
    try {
      const res = await generateWorkout(params)
      if (res.success) {
        setResult(res.workout)
      }
    } catch (error) {
      console.error(error)
      alert("Erro ao gerar treino")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex h-screen w-full bg-[#131313] text-[#e5e2e1] font-body selection:bg-[#c3f400] selection:text-on-primary-fixed overflow-hidden flex-col">
      {/* TopAppBar */}
      <header className="flex justify-between items-center px-6 py-4 w-full bg-[#131313] z-50 border-b border-[#353534]/50">
        <div className="flex items-center gap-4">
          <Link href="/dashboard">
            <span className="material-symbols-outlined text-[#CCFF00] cursor-pointer hover:opacity-80 transition-opacity">arrow_back</span>
          </Link>
          <h1 className="font-lexend font-bold text-xl tracking-tight uppercase text-white font-headline">Gerador com IA</h1>
        </div>
      </header>

      <main className="flex-1 overflow-y-auto p-6 md:p-10 custom-scrollbar">
        <div className="max-w-3xl mx-auto">
          {!result ? (
            <div className="space-y-8 bg-surface-container-low rounded-3xl p-8 border border-white/5 shadow-xl">
              <div className="text-center mb-8">
                <span className="material-symbols-outlined text-6xl text-[#CCFF00] mb-4">smart_toy</span>
                <h2 className="text-3xl font-bold font-headline text-white mb-2">Personal Trainer IA</h2>
                <p className="text-on-surface-variant">Configure os parâmetros e deixe a IA criar o treino perfeito para hoje.</p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label className="text-sm font-bold uppercase tracking-wider text-on-surface-variant ml-1">Foco Principal</label>
                  <select 
                    value={params.focus}
                    onChange={(e) => setParams({...params, focus: e.target.value})}
                    className="w-full h-14 bg-surface-container-high border-none rounded-xl px-4 text-white focus:ring-2 focus:ring-[#c3f400] font-medium appearance-none"
                  >
                    <option>Emagrecimento</option>
                    <option>Força</option>
                    <option>Mobilidade</option>
                    <option>Resistência</option>
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold uppercase tracking-wider text-on-surface-variant ml-1">Tempo Disponível (min)</label>
                  <input 
                    type="number"
                    value={params.duration}
                    onChange={(e) => setParams({...params, duration: Number(e.target.value)})}
                    className="w-full h-14 bg-surface-container-high border-none rounded-xl px-4 text-white focus:ring-2 focus:ring-[#c3f400] font-medium"
                    min="15" max="120" step="5"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold uppercase tracking-wider text-on-surface-variant ml-1">Intensidade</label>
                  <div className="flex gap-2">
                    {['Leve', 'Moderado', 'Intenso'].map((level) => (
                      <button 
                        key={level}
                        onClick={() => setParams({...params, intensity: level as WorkoutGenerationParams["intensity"]})}
                        className={`flex-1 py-3 rounded-xl font-bold transition-colors ${params.intensity === level ? 'bg-[#CCFF00] text-[#161E00]' : 'bg-surface-container-high text-white/70 hover:bg-white/10'}`}
                      >
                        {level}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold uppercase tracking-wider text-on-surface-variant ml-1">Local</label>
                  <div className="flex gap-2">
                    {['Casa', 'Academia', 'Ar Livre'].map((env) => (
                      <button 
                        key={env}
                        onClick={() => setParams({...params, environment: env as WorkoutGenerationParams["environment"]})}
                        className={`flex-1 py-3 rounded-xl font-bold transition-colors ${params.environment === env ? 'bg-[#CCFF00] text-[#161E00]' : 'bg-surface-container-high text-white/70 hover:bg-white/10'}`}
                      >
                        {env}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="space-y-2 md:col-span-2">
                  <label className="text-sm font-bold uppercase tracking-wider text-on-surface-variant ml-1">Limitações Físicas (Opcional)</label>
                  <input 
                    type="text"
                    value={params.limitation}
                    onChange={(e) => setParams({...params, limitation: e.target.value})}
                    placeholder="Ex: Dor no joelho direito, hipertensão..."
                    className="w-full h-14 bg-surface-container-high border-none rounded-xl px-4 text-white focus:ring-2 focus:ring-[#c3f400] font-medium"
                  />
                </div>
              </div>

              <button 
                onClick={handleGenerate}
                disabled={loading}
                className="w-full h-16 bg-[#CCFF00] text-[#161E00] font-black text-xl rounded-2xl shadow-[0_0_30px_rgba(204,255,0,0.2)] hover:scale-[1.02] active:scale-95 transition-all mt-8 flex items-center justify-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <span className="material-symbols-outlined animate-spin font-bold">progress_activity</span>
                ) : (
                  <>
                    <span className="material-symbols-outlined font-bold">magic_button</span>
                    GERAR TREINO COM IA
                  </>
                )}
              </button>
            </div>
          ) : (
            <div className="space-y-6">
              <div className="bg-[#ccff00]/10 border border-[#ccff00]/30 rounded-2xl p-6 text-center">
                <span className="material-symbols-outlined text-5xl text-[#ccff00] mb-2">check_circle</span>
                <h2 className="text-2xl font-bold text-white font-headline">Treino Gerado com Sucesso!</h2>
              </div>
              
              <div className="bg-surface-container-low rounded-3xl p-8 border border-white/5">
                <h3 className="text-3xl font-black font-headline text-[#CCFF00] mb-2">{result.titulo || result.title}</h3>
                <p className="text-on-surface-variant mb-6">{result.descricao || result.description}</p>
                
                <div className="flex gap-4 mb-8">
                  <div className="bg-surface-container-high rounded-xl px-4 py-2 text-sm font-bold"><span className="text-white/50 mr-2">Tempo</span>{result.duracao_minutos || result.duration} min</div>
                  <div className="bg-surface-container-high rounded-xl px-4 py-2 text-sm font-bold"><span className="text-white/50 mr-2">Foco</span>{result.foco || params.focus}</div>
                </div>

                <div className="space-y-4">
                  <h4 className="font-bold uppercase tracking-wider text-sm text-white/50 mb-4">Exercícios</h4>
                  {(result.conteudo_json || result.exercises || []).map((ex, i: number) => (
                    <div key={i} className="bg-surface-container-high p-4 rounded-2xl flex items-center justify-between border border-transparent hover:border-white/10 transition-colors">
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-full bg-[#ccff00]/20 text-[#ccff00] flex items-center justify-center font-bold">{i + 1}</div>
                        <div>
                          <h5 className="font-bold text-white">{ex.title}</h5>
                          <p className="text-xs text-white/50">{ex.type}</p>
                        </div>
                      </div>
                      <div className="font-black text-[#CCFF00]">{ex.reps}</div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="flex gap-4 mt-6">
                <Link href="/dashboard" className="flex-1 py-4 text-center rounded-xl bg-surface-container-high text-white font-bold hover:bg-white/10 transition-colors">
                  Voltar ao Dashboard
                </Link>
                <Link href="/workout/active" className="flex-2 py-4 text-center rounded-xl bg-[#CCFF00] text-[#161E00] font-black uppercase tracking-widest hover:scale-[1.02] active:scale-95 transition-all shadow-lg">
                  INICIAR AGORA
                </Link>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  )
}
