import React, { useState } from 'react';
import { Building2, ArrowRight, Loader2, CheckCircle2, LogOut, Clock, Briefcase } from 'lucide-react';
import { HybridBackend } from '../services/backend.ts';

interface CreateClinicViewProps {
  onCreated: () => void;
}

function getStoredUser(): { nome?: string; role?: string } {
  try { return JSON.parse(localStorage.getItem('SCOREODONTO_USER_DATA') || '{}'); } catch { return {}; }
}

function applyWorkspace(result: any, userRole: string) {
  const ws = {
    id: result.clinica.id,
    nome: result.clinica.nome_fantasia,
    cor: '#2563eb',
    role: userRole,
  };
  localStorage.setItem('SCOREODONTO_WORKSPACES', JSON.stringify([ws]));
  localStorage.setItem('SCOREODONTO_ACTIVE_WORKSPACE', JSON.stringify(ws));
}

export const CreateClinicView: React.FC<CreateClinicViewProps> = ({ onCreated }) => {
  const storedUser = getStoredUser();
  const userRole = storedUser.role || 'donoclinica';
  const isConsultorio = userRole === 'donoconsultorio';
  const label = isConsultorio ? 'CONSULTÓRIO' : 'CLÍNICA';

  const [nome, setNome] = useState('');
  const [documento, setDocumento] = useState('');
  const [loading, setLoading] = useState(false);
  const [skipping, setSkipping] = useState(false);
  const [error, setError] = useState('');
  const [done, setDone] = useState(false);

  const doCreate = async (nomeFinal: string, doc?: string) => {
    const result = await HybridBackend.createClinica(nomeFinal.trim(), doc?.trim() || undefined);
    if (!result.success) return result;
    applyWorkspace(result, userRole);
    return result;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!nome.trim()) return;
    setLoading(true);
    setError('');
    const result = await doCreate(nome, documento);
    setLoading(false);
    if (!result.success) { setError(result.message || `Erro ao criar ${label.toLowerCase()}.`); return; }
    setDone(true);
    setTimeout(() => { window.location.href = '/dashboard'; }, 1800);
  };

  const handleSkip = async () => {
    setSkipping(true);
    const autoNome = storedUser.nome ? `${storedUser.nome} - ${label}` : `MEU ${label}`;
    const result = await doCreate(autoNome);
    setSkipping(false);
    if (!result.success) { setError(result.message || 'Erro ao configurar. Tente novamente.'); return; }
    window.location.href = '/dashboard';
  };

  if (done) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="max-w-md w-full text-center">
          <CheckCircle2 size={64} className="text-green-500 mx-auto mb-4" />
          <h2 className="text-2xl font-black text-gray-800 uppercase">{label} CRIADO!</h2>
          <p className="text-gray-500 text-sm mt-2 uppercase font-bold">Carregando seu painel...</p>
          <Loader2 className="animate-spin text-blue-600 mx-auto mt-6" size={28} />
        </div>
      </div>
    );
  }

  const headerColor = isConsultorio ? 'bg-emerald-600' : 'bg-blue-600';
  const Icon = isConsultorio ? Briefcase : Building2;
  const placeholder = isConsultorio ? 'EX: DR. SILVA - CONSULTÓRIO' : 'EX: CLÍNICA SORRISO';

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="max-w-md w-full bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100">
        <div className={`${headerColor} p-8 text-center`}>
          <div className="w-16 h-16 bg-white/20 rounded-xl flex items-center justify-center text-white mx-auto backdrop-blur-sm mb-4">
            <Icon size={32} />
          </div>
          <h1 className="text-2xl font-bold text-white uppercase tracking-wide">NOVO {label}</h1>
          <p className="text-white/70 text-xs font-bold uppercase mt-1">CONFIGURAÇÃO INICIAL DO SISTEMA</p>
        </div>

        <div className="p-8">
          <p className="text-xs text-gray-500 uppercase font-bold text-center mb-6">
            {isConsultorio
              ? 'Crie seu consultório para começar. Você pode configurar endereço e dados depois.'
              : 'Crie sua clínica para começar. O módulo de RX será provisionado automaticamente.'}
          </p>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-bold text-gray-500 mb-1 uppercase">NOME DO {label} *</label>
              <div className="relative">
                <Icon className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="text"
                  required
                  value={nome}
                  onChange={(e) => setNome(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm font-medium uppercase"
                  placeholder={placeholder}
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-bold text-gray-500 mb-1 uppercase">CNPJ / CPF (opcional)</label>
              <input
                type="text"
                value={documento}
                onChange={(e) => setDocumento(e.target.value)}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm font-medium"
                placeholder="00.000.000/0000-00"
              />
            </div>

            {error && (
              <div className="p-3 bg-red-50 text-red-600 text-xs font-bold uppercase rounded-lg border border-red-100 text-center">
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading || skipping || !nome.trim()}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-bold uppercase flex items-center justify-center gap-2 transition-all shadow-lg disabled:opacity-70 disabled:cursor-not-allowed mt-2"
            >
              {loading ? <><Loader2 className="animate-spin" size={18} /> CRIANDO...</> : <>CRIAR {label} <ArrowRight size={18} /></>}
            </button>
          </form>

          <div className="mt-3 p-3 bg-amber-50 border border-amber-100 rounded-xl">
            <p className="text-[10px] text-amber-700 font-bold uppercase text-center mb-2">
              Prefere configurar depois?
            </p>
            <button
              type="button"
              onClick={handleSkip}
              disabled={loading || skipping}
              className="w-full flex items-center justify-center gap-2 py-2.5 px-4 bg-white border border-amber-200 hover:bg-amber-50 text-amber-700 rounded-lg text-xs font-black uppercase tracking-wide transition-colors disabled:opacity-50"
            >
              {skipping ? <Loader2 className="animate-spin" size={14} /> : <Clock size={14} />}
              Entrar agora e criar {label.toLowerCase()} depois
            </button>
          </div>

          <button
            onClick={() => HybridBackend.logout()}
            className="mt-4 w-full flex items-center justify-center gap-2 text-xs text-gray-400 hover:text-gray-600 font-bold uppercase transition-colors"
          >
            <LogOut size={14} /> SAIR DA CONTA
          </button>
        </div>
      </div>
    </div>
  );
};
