import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { 
  UserPlus, Search, Plus, User, Phone, Mail, 
  Calendar, Clock, FileText, CheckCircle2,
  Filter, MoreVertical, X,
  BadgeCheck, MapPin, MessageSquare,
  TrendingUp, Users, ArrowRight,
  AlertCircle, CheckCircle, Clock3,
  Edit2, Trash2, UserCheck, Eye
} from 'lucide-react';
import api from '../../../store/api';

interface Enquiry {
  id: number;
  uid: string;
  full_name: string;
  email: string;
  phone: string;
  address: string;
  class_interested: string;
  source: string;
  enquiry_date: string;
  follow_up_date: string | null;
  status: 'new' | 'contacted' | 'visited' | 'enrolled' | 'not-interested' | 'closed';
  assigned_to?: number;
  assigned_to_name: string;
  notes: string;
  next_action: string;
}

export default function AdmissionEnquiry() {
  const [enquiries, setEnquiries] = useState<Enquiry[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [editingId, setEditingId] = useState<number | null>(null);
  
  // Convert to Student State
  const [showConvertModal, setShowConvertModal] = useState(false);
  const [convertingEnquiry, setConvertingEnquiry] = useState<Enquiry | null>(null);
  const [submittingConvert, setSubmittingConvert] = useState(false);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [convertFormData, setConvertFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    password: 'TempPassword123!',
    class_id: '',
    roll_number: ''
  });

  const [formData, setFormData] = useState({
    full_name: '',
    email: '',
    phone: '',
    address: '',
    class_interested: '',
    source: '',
    follow_up_date: '',
    notes: '',
    next_action: '',
    assigned_to: ''
  });

  const fetchEnquiries = async () => {
    try {
      setLoading(true);
      const response = await api.get('/front-office/enquiries');
      setEnquiries(response.data);
    } catch (error) {
      console.error('Error fetching enquiries:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await api.get('/users?role=admin');
      const data = response.data.users || response.data;
      setUsers(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };

  const fetchClasses = async () => {
    try {
      const response = await api.get('/classes');
      setClasses(response.data);
    } catch (error) {
      console.error('Error fetching classes:', error);
    }
  };

  useEffect(() => {
    fetchEnquiries();
    fetchUsers();
    fetchClasses();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingId) {
        await api.put(`/front-office/enquiries/${editingId}`, formData);
      } else {
        await api.post('/front-office/enquiries', formData);
      }
      setShowAddModal(false);
      setEditingId(null);
      setFormData({
        full_name: '',
        email: '',
        phone: '',
        address: '',
        class_interested: '',
        source: '',
        follow_up_date: '',
        notes: '',
        next_action: '',
        assigned_to: ''
      });
      fetchEnquiries();
    } catch (error) {
      console.error('Error saving enquiry:', error);
    }
  };

  const handleDeleteEnquiry = async (id: number) => {
    if (!confirm('Are you sure you want to delete this enquiry? This action cannot be undone.')) return;
    try {
      await api.delete(`/front-office/enquiries/${id}`);
      fetchEnquiries();
      setSuccessMsg('Enquiry deleted successfully.');
      setTimeout(() => setSuccessMsg(null), 3000);
    } catch (error) {
      console.error('Error deleting enquiry:', error);
    }
  };

  const handleOpenConvert = (e: Enquiry) => {
    const names = e.full_name.trim().split(/\s+/);
    const firstName = names[0] || '';
    const lastName = names.slice(1).join(' ') || '.';
    
    // Find if any class matches the class_interested text
    const matchedClass = classes.find(c => 
      c.name.toLowerCase().includes(e.class_interested.toLowerCase())
    );

    setConvertingEnquiry(e);
    setConvertFormData({
      first_name: firstName,
      last_name: lastName,
      email: e.email || '',
      phone: e.phone || '',
      password: 'TempPassword123!',
      class_id: matchedClass ? String(matchedClass.id) : '',
      roll_number: ''
    });
    setShowConvertModal(true);
  };

  const handleConvertSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!convertingEnquiry) return;
    try {
      setSubmittingConvert(true);
      setErrorMsg(null);
      
      // Step 1: Create Student User
      const userRes = await api.post('/users', {
        email: convertFormData.email,
        password: convertFormData.password,
        role: 'student',
        first_name: convertFormData.first_name,
        last_name: convertFormData.last_name,
        phone: convertFormData.phone,
        address: convertingEnquiry.address
      });
      
      const newStudent = userRes.data;
      
      // Step 2: Enroll in Class (if selected)
      if (convertFormData.class_id && newStudent && newStudent.id) {
        await api.post('/enrollments', {
          student_id: newStudent.id,
          class_id: parseInt(convertFormData.class_id),
          roll_number: convertFormData.roll_number || null,
          academic_year: new Date().getFullYear().toString()
        });
      }
      
      // Step 3: Update Enquiry status to 'enrolled'
      await api.put(`/front-office/enquiries/${convertingEnquiry.id}`, {
        status: 'enrolled'
      });
      
      setSuccessMsg(`Successfully converted ${convertingEnquiry.full_name} to student!`);
      setTimeout(() => setSuccessMsg(null), 4000);
      setShowConvertModal(false);
      setConvertingEnquiry(null);
      fetchEnquiries();
    } catch (err: any) {
      console.error('Conversion failed:', err);
      setErrorMsg(err.response?.data?.error || 'Failed to convert prospect to student. Please check inputs.');
    } finally {
      setSubmittingConvert(false);
    }
  };

  const handleUpdateStatus = async (id: number, status: string) => {
    try {
      await api.put(`/front-office/enquiries/${id}`, { status });
      fetchEnquiries();
    } catch (error) {
      console.error('Error updating enquiry status:', error);
    }
  };

  const filteredEnquiries = enquiries.filter(e => 
    e.full_name.toLowerCase().includes(search.toLowerCase()) ||
    e.phone.includes(search) ||
    e.class_interested.toLowerCase().includes(search.toLowerCase())
  );

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'new': return 'bg-blue-50/10 text-blue-500 border-blue-500/20';
      case 'contacted': return 'bg-amber-50/10 text-amber-500 border-amber-500/20';
      case 'visited': return 'bg-purple-50/10 text-purple-500 border-purple-500/20';
      case 'enrolled': return 'bg-emerald-50/10 text-emerald-500 border-emerald-500/20';
      case 'not-interested': return 'bg-red-50/10 text-red-500 border-red-500/20';
      default: return 'bg-slate-50/10 text-slate-500 border-slate-500/20';
    }
  };

  const stats = {
    total: enquiries.length,
    new: enquiries.filter(e => e.status === 'new').length,
    converted: enquiries.filter(e => e.status === 'enrolled').length,
    pending: enquiries.filter(e => e.status !== 'enrolled' && e.status !== 'not-interested' && e.status !== 'closed').length
  };

  return (
    <div className="p-6">
      {successMsg && (
        <div className="mb-6 p-4 bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 rounded-xl flex items-center gap-3 animate-in fade-in slide-in-from-top-4 duration-200">
          <CheckCircle2 size={20} />
          <span className="font-semibold text-sm">{successMsg}</span>
        </div>
      )}

      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-text flex items-center gap-2">
            <UserPlus className="text-primary" />
            Admission Enquiry CRM
          </h1>
          <p className="text-text-muted text-sm mt-1">Manage leads and potential student admissions</p>
        </div>
        <button
          onClick={() => {
            setEditingId(null);
            setFormData({
              full_name: '',
              email: '',
              phone: '',
              address: '',
              class_interested: '',
              source: '',
              follow_up_date: '',
              notes: '',
              next_action: '',
              assigned_to: ''
            });
            setShowAddModal(true);
          }}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors shadow-sm"
        >
          <Plus size={20} />
          New Enquiry
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        {[
          { label: 'Total Enquiries', value: stats.total, icon: Users, color: 'blue' },
          { label: 'New Leads', value: stats.new, icon: AlertCircle, color: 'amber' },
          { label: 'Active Pipeline', value: stats.pending, icon: Clock3, color: 'indigo' },
          { label: 'Converted', value: stats.converted, icon: CheckCircle, color: 'emerald' },
        ].map((s, i) => (
          <div key={i} className="bg-card p-6 rounded-xl border border-border shadow-sm flex items-center gap-4">
            <div className={`w-12 h-12 rounded-lg bg-${s.color}-500/10 text-${s.color}-500 flex items-center justify-center`}>
              <s.icon size={24} />
            </div>
            <div>
              <p className="text-sm text-text-muted font-medium">{s.label}</p>
              <p className="text-2xl font-bold text-text">{s.value}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
        <div className="p-4 border-b border-border flex flex-col md:flex-row gap-4 items-center justify-between bg-background-alt/50">
          <div className="relative w-full md:w-96">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={18} />
            <input
              type="text"
              placeholder="Search enquiries by name, phone or class..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm text-text"
            />
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-background-alt/50 border-b border-border text-xs uppercase tracking-wider text-text-muted font-semibold">
                <th className="px-6 py-4 font-semibold">Lead Info</th>
                <th className="px-6 py-4 font-semibold">Interest & Source</th>
                <th className="px-6 py-4 font-semibold">Timeline</th>
                <th className="px-6 py-4 font-semibold">Assigned To</th>
                <th className="px-6 py-4 font-semibold">Status</th>
                <th className="px-6 py-4 font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50 text-sm">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                    <div className="flex flex-col items-center gap-2">
                      <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
                      <span>Loading pipeline...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredEnquiries.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                    <UserPlus size={48} className="mx-auto mb-4 opacity-20" />
                    <p>No enquiries found</p>
                  </td>
                </tr>
              ) : (
                filteredEnquiries.map((e) => (
                  <tr key={e.id} className="hover:bg-background-alt/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-primary/10 text-primary flex items-center justify-center font-bold">
                          {e.full_name[0]}
                        </div>
                        <div>
                          <p className="font-semibold text-text">{e.full_name}</p>
                          <div className="flex items-center gap-3 text-xs text-text-muted mt-1">
                            <span className="flex items-center gap-1"><Phone size={12} /> {e.phone}</span>
                            <span className="flex items-center gap-1"><Mail size={12} /> {e.email}</span>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div>
                        <p className="text-text font-medium">{e.class_interested}</p>
                        <p className="text-xs text-text-muted mt-1">Source: {e.source}</p>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="space-y-1.5">
                        <div className="flex items-center gap-2 text-xs text-text-secondary">
                          <Calendar size={12} className="text-primary" />
                          <span className="font-medium">Enquired:</span>
                          <span>{new Date(e.enquiry_date).toLocaleDateString()}</span>
                        </div>
                        {e.follow_up_date && (
                          <div className="flex items-center gap-2 text-xs text-amber-500">
                            <Clock size={12} className="text-amber-500" />
                            <span className="font-medium">Follow-up:</span>
                            <span>{new Date(e.follow_up_date).toLocaleDateString()}</span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2 text-xs text-text-secondary">
                        <div className="w-6 h-6 rounded-full bg-background-alt flex items-center justify-center">
                          <User size={12} />
                        </div>
                        {e.assigned_to_name || 'Unassigned'}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[0.65rem] font-black uppercase border transition-all duration-200 ${getStatusColor(e.status)}`}>
                        {e.status.replace('-', ' ')}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        <select
                          className="text-xs border border-border bg-background text-text rounded px-2 py-1 outline-none focus:ring-1 focus:ring-primary mr-1"
                          value={e.status}
                          onChange={(evt) => handleUpdateStatus(e.id, evt.target.value)}
                        >
                          <option value="new">New</option>
                          <option value="contacted">Contacted</option>
                          <option value="visited">Visited</option>
                          <option value="enrolled">Enrolled</option>
                          <option value="not-interested">Not Interested</option>
                        </select>

                        {e.status !== 'enrolled' && (
                          <button
                            onClick={() => handleOpenConvert(e)}
                            className="p-1.5 text-text-muted hover:text-emerald-500 hover:bg-emerald-500/10 rounded-lg transition-colors"
                            title="Convert to Student"
                          >
                            <UserCheck size={15} />
                          </button>
                        )}
                        
                        <button
                          onClick={() => {
                            setEditingId(e.id);
                            setFormData({
                              full_name: e.full_name,
                              email: e.email || '',
                              phone: e.phone,
                              address: e.address || '',
                              class_interested: e.class_interested || '',
                              source: e.source || '',
                              follow_up_date: e.follow_up_date ? e.follow_up_date.split('T')[0] : '',
                              notes: e.notes || '',
                              next_action: e.next_action || '',
                              assigned_to: e.assigned_to ? String(e.assigned_to) : ''
                            });
                            setShowAddModal(true);
                          }}
                          className="p-1.5 text-text-muted hover:text-primary hover:bg-primary/10 rounded-lg transition-colors"
                          title="Edit Enquiry"
                        >
                          <Edit2 size={15} />
                        </button>

                        <button
                          onClick={() => handleDeleteEnquiry(e.id)}
                          className="p-1.5 text-text-muted hover:text-rose-600 hover:bg-rose-500/10 rounded-lg transition-colors"
                          title="Delete Enquiry"
                        >
                          <Trash2 size={15} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Enquiry Modal */}
      {showAddModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowAddModal(false)}>
          <div className="bg-card rounded-[2.5rem] shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-4 border-b border-border flex items-center justify-between bg-background-alt/50 relative">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <UserPlus size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-lg font-bold text-text flex items-center gap-2">
                  <UserPlus className="text-primary" size={20} />
                  {editingId ? 'Edit Admission Enquiry' : 'New Admission Enquiry'}
                </h2>
              </div>
              <button
                onClick={() => {
                  setShowAddModal(false);
                  setEditingId(null);
                  setFormData({
                    full_name: '',
                    email: '',
                    phone: '',
                    address: '',
                    class_interested: '',
                    source: '',
                    follow_up_date: '',
                    notes: '',
                    next_action: '',
                    assigned_to: ''
                  });
                }}
                className="relative z-10 p-2 text-text-muted hover:text-text hover:bg-background-alt rounded-lg transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleSubmit} className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <h3 className="text-sm font-bold text-primary uppercase tracking-wider">Prospect Details</h3>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Full Name*</label>
                    <input
                      required
                      type="text"
                      value={formData.full_name}
                      onChange={e => setFormData({ ...formData, full_name: e.target.value })}
                      className="form-input"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Phone Number*</label>
                      <input
                        required
                        type="text"
                        value={formData.phone}
                        onChange={e => setFormData({ ...formData, phone: e.target.value })}
                        className="form-input"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Email Address</label>
                      <input
                        type="email"
                        value={formData.email}
                        onChange={e => setFormData({ ...formData, email: e.target.value })}
                        className="form-input"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Residential Address</label>
                    <textarea
                      rows={2}
                      value={formData.address}
                      onChange={e => setFormData({ ...formData, address: e.target.value })}
                      className="form-input resize-none"
                    />
                  </div>
                </div>

                <div className="space-y-4">
                  <h3 className="text-sm font-bold text-primary uppercase tracking-wider">Interest & Assignment</h3>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Class/Grade Interested</label>
                    <input
                      type="text"
                      value={formData.class_interested}
                      onChange={e => setFormData({ ...formData, class_interested: e.target.value })}
                      className="form-input"
                      placeholder="e.g. Grade 1"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Source</label>
                      <select
                        value={formData.source}
                        onChange={e => setFormData({ ...formData, source: e.target.value })}
                        className="form-input"
                      >
                        <option value="">Select Source</option>
                        <option value="Social Media">Social Media</option>
                        <option value="Word of Mouth">Word of Mouth</option>
                        <option value="Newspaper">Newspaper</option>
                        <option value="Website">Website</option>
                        <option value="Flyer">Flyer</option>
                        <option value="Other">Other</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-text-secondary mb-1.5">Follow-up Date</label>
                      <input
                        type="date"
                        value={formData.follow_up_date}
                        onChange={e => setFormData({ ...formData, follow_up_date: e.target.value })}
                        className="form-input"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-text-secondary mb-1.5">Assign to Counselor</label>
                    <select
                      value={formData.assigned_to}
                      onChange={e => setFormData({ ...formData, assigned_to: e.target.value })}
                      className="form-input"
                    >
                      <option value="">Select Counselor</option>
                      {users.map(u => (
                        <option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6 mt-6">
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Enquiry Notes</label>
                  <textarea
                    rows={3}
                    value={formData.notes}
                    onChange={e => setFormData({ ...formData, notes: e.target.value })}
                    className="form-input resize-none"
                    placeholder="Key points from the conversation..."
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Next Action</label>
                  <textarea
                    rows={3}
                    value={formData.next_action}
                    onChange={e => setFormData({ ...formData, next_action: e.target.value })}
                    className="form-input resize-none"
                    placeholder="What needs to be done next?"
                  />
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-border flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddModal(false);
                    setEditingId(null);
                    setFormData({
                      full_name: '',
                      email: '',
                      phone: '',
                      address: '',
                      class_interested: '',
                      source: '',
                      follow_up_date: '',
                      notes: '',
                      next_action: '',
                      assigned_to: ''
                    });
                  }}
                  className="px-6 py-2 text-text-secondary hover:bg-background-alt rounded-lg transition-colors font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-8 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors shadow-lg shadow-primary/20 font-semibold"
                >
                  {editingId ? 'Save Changes' : 'Create Enquiry'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Convert to Student Modal */}
      {showConvertModal && convertingEnquiry && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowConvertModal(false)}>
          <div className="bg-card rounded-[2.5rem] shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 py-4 border-b border-border flex items-center justify-between bg-background-alt/50 relative">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <UserCheck size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-lg font-bold text-text flex items-center gap-2">
                  <UserCheck className="text-emerald-500" size={20} />
                  Convert Lead to Registered Student
                </h2>
              </div>
              <button
                onClick={() => {
                  setShowConvertModal(false);
                  setConvertingEnquiry(null);
                  setErrorMsg(null);
                }}
                className="relative z-10 p-2 text-text-muted hover:text-text hover:bg-background-alt rounded-lg transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleConvertSubmit} className="p-6">
              {errorMsg && (
                <div className="mb-6 p-4 bg-rose-500/10 border border-rose-500/20 text-rose-500 rounded-xl flex items-center gap-3">
                  <AlertCircle size={20} />
                  <span className="font-semibold text-sm">{errorMsg}</span>
                </div>
              )}

              <p className="text-text-secondary text-sm mb-6">
                Onboarding <strong>{convertingEnquiry.full_name}</strong> as a student. This will automatically create their student login and assign them to an academic class.
              </p>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">First Name*</label>
                  <input
                    required
                    type="text"
                    value={convertFormData.first_name}
                    onChange={e => setConvertFormData({ ...convertFormData, first_name: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Last Name*</label>
                  <input
                    required
                    type="text"
                    value={convertFormData.last_name}
                    onChange={e => setConvertFormData({ ...convertFormData, last_name: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Email Address*</label>
                  <input
                    required
                    type="email"
                    value={convertFormData.email}
                    onChange={e => setConvertFormData({ ...convertFormData, email: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Phone Number</label>
                  <input
                    type="text"
                    value={convertFormData.phone}
                    onChange={e => setConvertFormData({ ...convertFormData, phone: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Temporary Password*</label>
                  <input
                    required
                    type="text"
                    value={convertFormData.password}
                    onChange={e => setConvertFormData({ ...convertFormData, password: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Assign to Class*</label>
                  <select
                    required
                    value={convertFormData.class_id}
                    onChange={e => setConvertFormData({ ...convertFormData, class_id: e.target.value })}
                    className="form-input"
                  >
                    <option value="">Select Academic Class</option>
                    {classes.map(c => (
                      <option key={c.id} value={c.id}>{c.name} {c.section}</option>
                    ))}
                  </select>
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold text-text-secondary mb-1.5">Roll Number / Student ID</label>
                  <input
                    type="text"
                    value={convertFormData.roll_number}
                    onChange={e => setConvertFormData({ ...convertFormData, roll_number: e.target.value })}
                    className="form-input"
                    placeholder="e.g. 2026-009"
                  />
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-border flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => {
                    setShowConvertModal(false);
                    setConvertingEnquiry(null);
                    setErrorMsg(null);
                  }}
                  className="px-6 py-2 text-text-secondary hover:bg-background-alt rounded-lg transition-colors font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submittingConvert}
                  className="px-8 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors shadow-lg shadow-emerald-600/20 font-semibold disabled:opacity-50 flex items-center gap-2"
                >
                  {submittingConvert ? 'Processing...' : 'Complete Conversion'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}
