import React, { useState, useEffect } from 'react';
import { SettingsService } from '../services/api';
import api from '../services/api';
import { ShieldCheck, Save, AlertCircle, Palette } from 'lucide-react';

function Section({ icon: Icon, title, subtitle, children }: {
  icon: any; title: string; subtitle: string; children: React.ReactNode
}) {
  return (
    <div className="bg-slate-900/50 border border-slate-800 rounded-3xl p-8 relative overflow-hidden">
      <div className="flex items-center gap-4 mb-8">
        <div className="p-3 bg-cyan-500/10 text-cyan-400 rounded-2xl">
          <Icon size={28} />
        </div>
        <div>
          <h3 className="text-xl font-bold text-white">{title}</h3>
          <p className="text-sm text-slate-500">{subtitle}</p>
        </div>
      </div>
      {children}
      <div className="absolute -bottom-24 -right-24 w-64 h-64 bg-cyan-500/5 rounded-full blur-3xl pointer-events-none" />
    </div>
  );
}


function SaveFeedback({ saved }: { saved: boolean }) {
  if (!saved) return null;
  return (
    <span className="text-emerald-400 font-medium text-sm animate-in fade-in slide-in-from-left-4">
      ✅ Salvo com sucesso!
    </span>
  );
}

export default function SettingsPage() {
  // Asaas
  const [asaasKey, setAsaasKey]     = useState('');
  const [asaasSaved, setAsaasSaved] = useState(false);
  const [asaasLoading, setAsaasLoading] = useState(false);

  // Identidade Visual (tenant_config)
  const [branding, setBranding] = useState({
    primary_color:   '#f59e0b',
    secondary_color: '#10b981',
    logo_url:        '',
    favicon_url:     '',
    contact_email:   '',
    contact_phone:   '',
    app_url:         '',
  });
  const [brandLoading, setBrandLoading] = useState(false);
  const [brandSaved, setBrandSaved]     = useState(false);

  useEffect(() => {
    SettingsService.getAsaasKey().then(d => setAsaasKey(d.key || ''));
    api.get('/tenant/config').then(r => {
      const d = r.data;
      setBranding({
        primary_color:   d.primary_color   || '#f59e0b',
        secondary_color: d.secondary_color || '#10b981',
        logo_url:        d.logo_url        || '',
        favicon_url:     d.favicon_url     || '',
        contact_email:   d.contact_email   || '',
        contact_phone:   d.contact_phone   || '',
        app_url:         d.app_url         || '',
      });
    }).catch(() => {});
  }, []);

  const handleAsaasSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setAsaasLoading(true);
    try {
      await SettingsService.saveAsaasKey(asaasKey);
      setAsaasSaved(true);
      setTimeout(() => setAsaasSaved(false), 3000);
    } catch {
      alert('Erro ao salvar a chave Asaas');
    } finally {
      setAsaasLoading(false);
    }
  };

  const handleBrandSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setBrandLoading(true);
    try {
      await api.put('/tenant/config', branding);
      setBrandSaved(true);
      setTimeout(() => setBrandSaved(false), 3000);
    } catch {
      alert('Erro ao salvar identidade visual');
    } finally {
      setBrandLoading(false);
    }
  };

  const inputCls = "w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-white placeholder:text-slate-600 focus:outline-none focus:ring-2 ring-cyan-500 transition-all";
  const labelCls = "block text-sm font-semibold text-slate-400 mb-2";

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header>
        <h2 className="text-3xl font-bold text-white">Configurações</h2>
        <p className="text-slate-400 mt-1">Gerencie integrações, pagamentos e identidade visual do tenant.</p>
      </header>

      <div className="max-w-2xl space-y-8">

        {/* Identidade Visual */}
        <Section icon={Palette} title="Identidade Visual" subtitle="Cores e dados de exibição do tenant">
          <form onSubmit={handleBrandSave} className="space-y-5">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className={labelCls}>Cor Primária</label>
                <div className="flex items-center gap-3">
                  <input type="color" value={branding.primary_color}
                    onChange={e => setBranding(b => ({ ...b, primary_color: e.target.value }))}
                    className="w-12 h-12 rounded-xl cursor-pointer bg-slate-800 border border-slate-700 p-1"
                  />
                  <input type="text" value={branding.primary_color}
                    onChange={e => setBranding(b => ({ ...b, primary_color: e.target.value }))}
                    className={inputCls + ' font-mono'}
                  />
                </div>
              </div>
              <div>
                <label className={labelCls}>Cor Secundária</label>
                <div className="flex items-center gap-3">
                  <input type="color" value={branding.secondary_color}
                    onChange={e => setBranding(b => ({ ...b, secondary_color: e.target.value }))}
                    className="w-12 h-12 rounded-xl cursor-pointer bg-slate-800 border border-slate-700 p-1"
                  />
                  <input type="text" value={branding.secondary_color}
                    onChange={e => setBranding(b => ({ ...b, secondary_color: e.target.value }))}
                    className={inputCls + ' font-mono'}
                  />
                </div>
              </div>
            </div>

            <div>
              <label className={labelCls}>URL do Logo</label>
              <input type="text" value={branding.logo_url} placeholder="https://..."
                onChange={e => setBranding(b => ({ ...b, logo_url: e.target.value }))}
                className={inputCls}
              />
            </div>

            <div>
              <label className={labelCls}>URL do Favicon</label>
              <input type="text" value={branding.favicon_url} placeholder="https://..."
                onChange={e => setBranding(b => ({ ...b, favicon_url: e.target.value }))}
                className={inputCls}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className={labelCls}>E-mail de Contato</label>
                <input type="email" value={branding.contact_email} placeholder="contato@empresa.com"
                  onChange={e => setBranding(b => ({ ...b, contact_email: e.target.value }))}
                  className={inputCls}
                />
              </div>
              <div>
                <label className={labelCls}>Telefone de Contato</label>
                <input type="text" value={branding.contact_phone} placeholder="(00) 00000-0000"
                  onChange={e => setBranding(b => ({ ...b, contact_phone: e.target.value }))}
                  className={inputCls}
                />
              </div>
            </div>

            <div>
              <label className={labelCls}>URL Pública do App</label>
              <input type="text" value={branding.app_url} placeholder="https://alemaoconveniencias.com.br"
                onChange={e => setBranding(b => ({ ...b, app_url: e.target.value }))}
                className={inputCls}
              />
              <p className="mt-2 text-xs text-slate-500 flex items-center gap-1.5">
                <AlertCircle size={14} />
                Usada nos links enviados por WhatsApp e e-mail.
              </p>
            </div>

            {/* Preview */}
            <div className="rounded-2xl border border-slate-700 p-4 flex items-center gap-4">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold text-lg shrink-0"
                style={{ background: branding.primary_color }}>
                {branding.logo_url
                  ? <img src={branding.logo_url} className="w-full h-full object-contain rounded-xl" alt="logo" />
                  : 'A'}
              </div>
              <div>
                <div className="text-sm font-bold text-white">Preview do Branding</div>
                <div className="flex gap-2 mt-1">
                  <span className="w-4 h-4 rounded-full inline-block" style={{ background: branding.primary_color }} />
                  <span className="w-4 h-4 rounded-full inline-block" style={{ background: branding.secondary_color }} />
                  <span className="text-xs text-slate-500">{branding.primary_color} / {branding.secondary_color}</span>
                </div>
              </div>
            </div>

            <div className="pt-2 flex items-center gap-4">
              <button disabled={brandLoading} type="submit"
                className="bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 text-slate-950 font-bold px-6 py-3 rounded-xl flex items-center gap-2 transition-all shadow-lg shadow-cyan-500/20">
                <Save size={18} />
                {brandLoading ? 'Salvando...' : 'Salvar Identidade Visual'}
              </button>
              <SaveFeedback saved={brandSaved} />
            </div>
          </form>
        </Section>

        {/* Asaas */}
        <Section icon={ShieldCheck} title="Gateway de Pagamento (Asaas)" subtitle="Configuração de Cobranças PIX Automatizadas">
          <form onSubmit={handleAsaasSave} className="space-y-6">
            <div>
              <label className={labelCls}>ASAAS API KEY</label>
              <input type="password" value={asaasKey}
                onChange={e => setAsaasKey(e.target.value)}
                placeholder="Ex: $aact_..."
                className={inputCls}
              />
              <p className="mt-2 text-xs text-slate-500 flex items-center gap-1.5">
                <AlertCircle size={14} />
                Use <b>sandbox_local</b> para testar sem cobrar dinheiro real.
              </p>
            </div>
            <div className="pt-2 flex items-center gap-4">
              <button disabled={asaasLoading} type="submit"
                className="bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 text-slate-950 font-bold px-6 py-3 rounded-xl flex items-center gap-2 transition-all shadow-lg shadow-cyan-500/20">
                <Save size={18} />
                {asaasLoading ? 'Salvando...' : 'Salvar Alterações'}
              </button>
              <SaveFeedback saved={asaasSaved} />
            </div>
          </form>
        </Section>

      </div>
    </div>
  );
}
