import React, { useState, useEffect } from 'react';
import { supabase, createAdminClient } from '../supabase';

const DEPARTMENTS = ['AIDS', 'CSBS', 'CSE', 'CCE', 'MECH', 'VLSI', 'BIO-TECH', 'AIML', 'ECE', 'H&S'];

const UserManagementView: React.FC = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    department: '',
    phone: '',
    role: 'Faculty',
    password: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const [coordinators, setCoordinators] = useState<any[]>([]);
  const [isLoadingList, setIsLoadingList] = useState(true);

  useEffect(() => {
    fetchCoordinators();
  }, []);

  const fetchCoordinators = async () => {
    try {
      const { data: adminData, error: adminError } = await supabase
        .from('Facultyusers')
        .select('*')
        .order('name', { ascending: true });

      if (adminError && !adminError.message.includes('not found')) throw adminError;

      // Sort by role: HOD first, then Faculty. Alphabetical within roles.
      const sorted = (adminData || []).sort((a, b) => {
        if (a.role === 'HOD' && b.role !== 'HOD') return -1;
        if (a.role !== 'HOD' && b.role === 'HOD') return 1;
        return a.name.localeCompare(b.name);
      });

      setCoordinators(sorted);
    } catch (err) {
      console.error("Error fetching coordinators:", err);
    } finally {
      setIsLoadingList(false);
    }
  };

  const generatePassword = () => {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
    let pass = "";
    for (let i = 0; i < 12; i++) {
      pass += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setFormData(prev => ({ ...prev, password: pass }));
    setShowPassword(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleDeleteUser = async (id: string, name: string, email: string) => {
    if (!window.confirm(`Are you sure you want to remove ${name}? This will delete their profile but they may still exist in Auth.`)) return;

    try {
      const { error } = await supabase.from('Facultyusers').delete().eq('id', id);
      if (error) throw error;
      
      setCoordinators(prev => prev.filter(c => c.id !== id));
    } catch (err: any) {
      alert("Error deleting user: " + err.message);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);
    setSuccess(null);

    try {
      // Use a separate client that doesn't persist sessions to avoid logging out the admin
      const adminClient = createAdminClient();
      
      const { data, error: signUpError } = await adminClient.auth.signUp({
        email: formData.email,
        password: formData.password,
        options: {
          data: {
            name: formData.name,
            role: formData.role === 'HOD' ? 'HOD' : 'COORDINATOR',
            department: formData.department,
          }
        }
      });

      if (signUpError) throw signUpError;

      if (data.user) {
        const { error: adminDbError } = await supabase.from('Facultyusers').insert({
          id: data.user.id,
          name: formData.name,
          email: formData.email,
          phone: formData.phone,
          department: formData.department,
          role: formData.role,
          updated_at: new Date().toISOString()
        });

        if (adminDbError) throw adminDbError;

        setSuccess(`User ${formData.name} created successfully! Password: ${formData.password}`);
        setFormData({ name: '', email: '', department: '', phone: '', role: 'Faculty', password: '' });
        fetchCoordinators();
      }
    } catch (err: any) {
      console.error("User creation error:", err);
      setError(err.message || "Failed to create user.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="animate-in fade-in slide-in-from-bottom-10 duration-700">
      <div className="mb-10">
        <h2 className="text-4xl font-black text-slate-900 uppercase tracking-tighter mb-2">
          USER <span className="text-sky-500">MANAGEMENT</span>
        </h2>
        <p className="text-slate-400 text-xs font-bold uppercase tracking-widest">
          Provision access for Event Coordinators
        </p>
      </div>

      <div className="grid lg:grid-cols-2 gap-10">
        {/* Creation Card */}
        <div className="bg-white rounded-[2.5rem] border border-slate-100 p-10 shadow-xl shadow-slate-200/50 relative overflow-hidden group">
          <div className="absolute top-0 right-0 w-32 h-32 bg-sky-500/5 rounded-full -translate-y-1/2 translate-x-1/2 group-hover:scale-150 transition-transform duration-700"></div>
          
          <form onSubmit={handleSubmit} className="space-y-6 relative z-10">
            <div className="grid gap-6">
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-2">Full Name</label>
                <input 
                  required
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  placeholder="e.g. Dr. John Doe"
                  className="w-full bg-slate-50 border-none rounded-2xl px-6 py-4 text-xs font-bold outline-none focus:ring-2 focus:ring-sky-500 transition-all"
                />
              </div>

              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-2">Assign Role</label>
                <div className="flex bg-slate-50 p-1.5 rounded-2xl gap-2">
                  {['Faculty', 'HOD'].map(r => (
                    <button
                      key={r}
                      type="button"
                      onClick={() => setFormData(p => ({ ...p, role: r }))}
                      className={`flex-1 py-3 rounded-xl text-[9px] font-black uppercase tracking-widest transition-all ${
                        formData.role === r 
                          ? 'bg-white text-sky-600 shadow-sm' 
                          : 'text-slate-400 hover:text-slate-600'
                      }`}
                    >
                      {r}
                    </button>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-2">Gmail Address</label>
                  <input 
                    required
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    placeholder="coordinator@gmail.com"
                    className="w-full bg-slate-50 border-none rounded-2xl px-6 py-4 text-xs font-bold outline-none focus:ring-2 focus:ring-sky-500 transition-all"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-2">Phone Number</label>
                  <input 
                    required
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="e.g. 9876543210"
                    className="w-full bg-slate-50 border-none rounded-2xl px-6 py-4 text-xs font-bold outline-none focus:ring-2 focus:ring-sky-500 transition-all"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-2">Department</label>
                  <select 
                    required
                    name="department"
                    value={formData.department}
                    onChange={handleInputChange}
                    className="w-full bg-slate-50 border-none rounded-2xl px-6 py-4 text-xs font-bold outline-none focus:ring-2 focus:ring-sky-500 transition-all appearance-none"
                  >
                    <option value="">Select Dept</option>
                    {DEPARTMENTS.map(dept => <option key={dept} value={dept}>{dept}</option>)}
                  </select>
                </div>
                <div className="space-y-2">
                  <div className="flex justify-between items-center px-2">
                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Password</label>
                    <button 
                      type="button" 
                      onClick={generatePassword}
                      className="text-[8px] font-black text-sky-500 uppercase hover:underline"
                    >
                      Generate
                    </button>
                  </div>
                  <div className="relative">
                    <input 
                      required
                      type={showPassword ? 'text' : 'password'}
                      name="password"
                      value={formData.password}
                      onChange={handleInputChange}
                      placeholder="••••••••"
                      className="w-full bg-slate-50 border-none rounded-2xl px-6 py-4 text-xs font-bold outline-none focus:ring-2 focus:ring-sky-500 transition-all"
                    />
                    <button 
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-300 hover:text-sky-500 transition-colors"
                    >
                      <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {error && (
              <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl flex items-center gap-3 text-rose-600 text-[10px] font-bold uppercase">
                <i className="fas fa-exclamation-circle"></i>
                {error}
              </div>
            )}

            {success && (
              <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-2xl flex items-center gap-3 text-emerald-600 text-[10px] font-bold uppercase">
                <i className="fas fa-check-circle"></i>
                {success}
              </div>
            )}

            <button 
              type="submit" 
              disabled={isSubmitting}
              className="w-full py-5 bg-sky-500 text-white rounded-2xl font-black uppercase text-xs tracking-[0.2em] shadow-xl shadow-sky-500/20 hover:bg-sky-600 transition-all active:scale-95 disabled:opacity-50"
            >
              {isSubmitting ? 'Creating User...' : 'Create Event Coordinator'}
            </button>
          </form>
        </div>

        {/* Info Card */}
        <div className="space-y-6">
          <div className="bg-slate-900 rounded-[2.5rem] p-10 text-white relative overflow-hidden">
            <div className="absolute top-0 right-0 p-10 opacity-10">
              <i className="fas fa-user-shield text-9xl"></i>
            </div>
            <h3 className="text-2xl font-black uppercase tracking-tight mb-4 relative z-10">Security Protocol</h3>
            <p className="text-slate-400 text-sm font-medium leading-relaxed mb-8 relative z-10">
              Coordinators created here will have immediate access to the Event Coordinator Portal. 
              They will be stored in the <code className="text-sky-400 bg-sky-400/10 px-2 py-1 rounded">Facultyusers</code> table.
            </p>
            <ul className="space-y-4 relative z-10">
              {[
                'Automatic role assignment (ADMIN)',
                'Departmental scoping enabled',
                'Profile synchronization active',
                'Sign-up restricted for public'
              ].map((text, i) => (
                <li key={i} className="flex items-center gap-3 text-[10px] font-bold uppercase tracking-widest text-slate-300">
                  <i className="fas fa-check text-sky-500"></i>
                  {text}
                </li>
              ))}
            </ul>
          </div>

          <div className="bg-sky-50 rounded-[2.5rem] p-10 border border-sky-100">
            <h4 className="text-sky-900 font-black uppercase text-xs tracking-widest mb-4">Important Note</h4>
            <p className="text-sky-700/70 text-xs font-medium leading-relaxed">
              Creating a user via this interface will register them in Supabase Auth. 
              Ensure the Gmail address is valid as it will be used for portal access.
            </p>
          </div>
        </div>
      </div>
      <div className="mt-20">
        <div className="mb-8">
          <h3 className="text-2xl font-black text-slate-900 uppercase tracking-tighter">
            EXISTING <span className="text-sky-500">COORDINATORS</span>
          </h3>
          <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest">
            Manage active event coordinators
          </p>
        </div>

        {isLoadingList ? (
          <div className="flex justify-center py-20">
            <div className="w-8 h-8 border-4 border-sky-500 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : coordinators.length === 0 ? (
          <div className="bg-slate-50 rounded-[2rem] p-12 text-center border-2 border-dashed border-slate-200">
            <p className="text-slate-400 font-bold uppercase text-xs tracking-widest">No coordinators found</p>
          </div>
        ) : (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {coordinators.map((coord) => (
              <div key={coord.id} className="bg-white rounded-3xl border border-slate-100 p-6 shadow-sm hover:shadow-md transition-all group relative overflow-hidden">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-sky-500/10 flex items-center justify-center text-sky-500">
                      <i className="fas fa-user-tie text-xl"></i>
                    </div>
                    <div>
                      <h4 className="font-black text-slate-900 uppercase text-xs tracking-tight">{coord.name}</h4>
                      <div className="flex items-center gap-2">
                        <p className="text-sky-500 text-[9px] font-black uppercase tracking-widest">
                          {coord.department || coord.dept}
                        </p>
                        <span className={`text-[7px] font-black uppercase px-2 py-0.5 rounded-full ${
                          coord.role === 'HOD' ? 'bg-orange-500 text-white' : 'bg-slate-100 text-slate-400'
                        }`}>
                          {coord.role || 'Faculty'}
                        </span>
                      </div>
                    </div>
                  </div>
                  <button 
                    onClick={() => handleDeleteUser(coord.id, coord.name, coord.email)}
                    className="w-8 h-8 rounded-xl bg-rose-50 text-rose-500 flex items-center justify-center hover:bg-rose-500 hover:text-white transition-all"
                  >
                    <i className="fas fa-trash-alt text-xs"></i>
                  </button>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-slate-400">
                    <i className="fas fa-envelope text-[10px]"></i>
                    <span className="text-[10px] font-medium">{coord.email}</span>
                  </div>
                  {coord.phone && (
                    <div className="flex items-center gap-2 text-slate-400">
                      <i className="fas fa-phone text-[10px]"></i>
                      <span className="text-[10px] font-medium">{coord.phone}</span>
                    </div>
                  )}
                </div>
                <div className="absolute bottom-0 right-0 p-4 opacity-5 group-hover:opacity-10 transition-opacity">
                  <i className="fas fa-id-badge text-6xl"></i>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default UserManagementView;
