"use client";
import React, { useState, useTransition } from 'react';
import { registrarInscripcion } from '@/app/actions/inscripcion';
import { CheckCircle2, User, Phone, MapPin, Mail, CreditCard, Users, Star } from 'lucide-react';
import Link from 'next/link';

export default function InscripcionForm({ cursoId, tituloCurso }: { cursoId: string, tituloCurso: string }) {
  const [isPending, startTransition] = useTransition();
  const [successMsg, setSuccessMsg] = useState('');
  const [errorMsg, setErrorMsg] = useState('');

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSuccessMsg('');
    setErrorMsg('');
    
    const formData = new FormData(e.currentTarget);
    formData.append('cursoId', cursoId);

    startTransition(async () => {
      const result = await registrarInscripcion(formData);
      if (result.success) {
        setSuccessMsg(result.message || 'Inscripción exitosa');
      } else {
        setErrorMsg(result.error || 'Error desconocido');
      }
    });
  };

  if (successMsg) {
    return (
      <div className="text-center py-10">
        <CheckCircle2 className="w-24 h-24 text-green-500 mx-auto mb-6" />
        <h3 className="text-3xl font-extrabold text-gray-900 mb-4">¡Registro Completado!</h3>
        <p className="text-gray-500 text-lg mb-8 max-w-md mx-auto">{successMsg}</p>
        <div className="bg-gray-50 rounded-xl p-6 mb-8 border border-gray-100 inline-block text-left w-full max-w-sm">
           <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Curso Reservado</p>
           <p className="text-[#1e2a47] font-bold text-lg">{tituloCurso}</p>
           <p className="text-gray-500 text-sm mt-3">Nuestro equipo se pondrá en contacto contigo muy pronto para los pasos de pago y formalización.</p>
        </div>
        <br/>
        <Link href="/" className="inline-block bg-[#1e2a47] text-white px-8 py-3 rounded-lg font-semibold hover:bg-[#111827] transition-colors">
          Volver al Inicio
        </Link>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {errorMsg && (
        <div className="bg-red-50 text-red-600 p-4 rounded-xl text-sm font-semibold border border-red-200">
          ⚠️ {errorMsg}
        </div>
      )}

      {/* ─── DATOS DEL ESTUDIANTE ─── */}
      <div>
        <h3 className="flex items-center gap-2 text-xl font-bold text-[#1e2a47] mb-6 border-b border-gray-100 pb-2">
          <User className="w-5 h-5 text-[#f57c00]" />
          Datos del Estudiante
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Nombre <span className="text-red-500">*</span></label>
            <input name="nombre" type="text" required
              className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
              placeholder="Ej. Carlos" />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Apellido <span className="text-red-500">*</span></label>
            <input name="apellido" type="text" required
              className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
              placeholder="Ej. Pérez" />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Cédula de Identidad <span className="text-red-500">*</span></label>
            <div className="relative">
              <CreditCard className="w-4 h-4 text-gray-400 absolute left-4 top-1/2 transform -translate-y-1/2" />
              <input name="cedula" type="text" required
                className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 pl-11 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
                placeholder="Ej. V-12345678" />
            </div>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Teléfono Personal <span className="text-red-500">*</span></label>
            <div className="relative">
              <Phone className="w-4 h-4 text-gray-400 absolute left-4 top-1/2 transform -translate-y-1/2" />
              <input name="telefono" type="text" required
                className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 pl-11 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
                placeholder="0414-XXXXXXX" />
            </div>
          </div>
          <div className="space-y-2 md:col-span-2">
            <label className="text-sm font-bold text-gray-700">Dirección Exacta <span className="text-red-500">*</span></label>
            <div className="relative">
              <MapPin className="w-4 h-4 text-gray-400 absolute left-4 top-4" />
              <textarea name="direccion" required rows={2}
                className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 pl-11 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
                placeholder="Av. Principal, Sector..." />
            </div>
          </div>
          <div className="space-y-2 md:col-span-2">
            <label className="text-sm font-bold text-gray-700">Correo Electrónico <span className="font-medium text-gray-400 font-normal">(Opcional)</span></label>
            <div className="relative">
              <Mail className="w-4 h-4 text-gray-400 absolute left-4 top-1/2 transform -translate-y-1/2" />
              <input name="email" type="email"
                className="w-full bg-gray-50 border border-gray-200 rounded-lg px-4 py-3 pl-11 outline-none focus:ring-2 focus:ring-[#0066ff] transition-all" 
                placeholder="tucorreo@ejemplo.com" />
            </div>
          </div>
        </div>
      </div>

      {/* ─── DATOS DEL REPRESENTANTE ─── */}
      <div className="bg-orange-50/50 p-6 md:p-8 rounded-2xl border border-orange-100">
        <h3 className="flex items-center gap-2 text-xl font-bold text-orange-800 mb-6 border-b border-orange-200 pb-2">
          <Users className="w-5 h-5" />
          Datos del Representante (O Contacto de Emergencia)
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2 md:col-span-2">
            <label className="text-sm font-bold text-gray-700">Nombre y Apellidos del Representante <span className="text-red-500">*</span></label>
            <input name="representanteNombre" type="text" required
              className="w-full bg-white border border-gray-200 rounded-lg px-4 py-3 outline-none focus:ring-2 focus:ring-orange-500 transition-all" 
              placeholder="Ej. María López" />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Teléfono del Representante <span className="text-red-500">*</span></label>
            <input name="representanteTelefono" type="text" required
              className="w-full bg-white border border-gray-200 rounded-lg px-4 py-3 outline-none focus:ring-2 focus:ring-orange-500 transition-all" 
              placeholder="0414-XXXXXXX" />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-bold text-gray-700">Parentesco con el Estudiante <span className="text-red-500">*</span></label>
            <select name="representanteParentesco" required
              className="w-full bg-white border border-gray-200 rounded-lg px-4 py-3 outline-none focus:ring-2 focus:ring-orange-500 transition-all text-gray-700">
              <option value="">Selecciona un parentesco...</option>
              <option value="MADRE">Madre</option>
              <option value="PADRE">Padre</option>
              <option value="ABUELO">Abuelo(a)</option>
              <option value="HERMANO">Hermano(a)</option>
              <option value="ESPOSO">Esposo(a) / Pareja</option>
              <option value="OTRO">Otro Familiar/Amigo</option>
            </select>
          </div>
        </div>
      </div>

      <div className="pt-6">
        <button type="submit" disabled={isPending}
          className="w-full bg-[#0066ff] hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white text-lg font-extrabold py-5 rounded-xl shadow-lg hover:shadow-xl transition-all shadow-[#0066ff]/20 flex justify-center items-center gap-2">
          {isPending ? 'Procesando tu inscripción...' : 
            <><Star className="w-5 h-5 fill-white" /> Formalizar Registro e Inscribirse</>
          }
        </button>
        <p className="text-center text-xs text-gray-400 mt-4 font-semibold">
          Al inscribirte aceptas los términos y condiciones de participación de CursosNirgua.
        </p>
      </div>
    </form>
  )
}
