import { API_BASE_URL } from '../../lib/config';
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Plus, 
  Search, 
  Trash2, 
  Layers, 
  RefreshCw, 
  AlertTriangle,
  Building2,
  GraduationCap,
  ChevronRight,
  X,
  CheckCircle2,
  Edit,
  Save
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { Pagination } from './Pagination';
import { useDialog } from '../../context/DialogContext';

interface ClassMapping {
  id: number;
  institution: string;
  department: string;
  academicYear: string;
  sections: string[];
  status: string;
}

const ritDepartments = ['AI&DS', 'AI&ML', 'CSE', 'CCE', 'CSBS', 'ECE', 'MECH', 'EE(VLSI)', 'BIOTECH', 'Placement Department', 'H&S Dept', 'Club', 'Centre'];
const rsbDepartments = ['PGDM'];
const years = ['1st Year', '2nd Year', '3rd Year', '4th Year'];

import rsbLogo from '../../assets/images/rsb_logo.png';
import ritLogo from '../../assets/images/college-logo.png';

export const ClassManagement: React.FC = () => {
  const { showAlert, showConfirm } = useDialog();
  const [classes, setClasses] = useState<ClassMapping[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [newSection, setNewSection] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  
  const [formData, setFormData] = useState({
    institution: 'RIT',
    department: 'AI&DS',
    academicYear: '1st Year',
    sections: [] as string[]
  });

  const [batches, setBatches] = useState<any[]>([]);
  const [newBatchName, setNewBatchName] = useState('');
  const [selectedBatchDept, setSelectedBatchDept] = useState('AI&DS');
  const [tempBatches, setTempBatches] = useState<any[]>([]);

  useEffect(() => {
    const deptBatches = batches.filter(b => b.department === selectedBatchDept);
    setTempBatches(JSON.parse(JSON.stringify(deptBatches)));
  }, [batches, selectedBatchDept]);

  const currentDepartments = formData.institution === 'RIT' ? ritDepartments : rsbDepartments;

  useEffect(() => {
    if (formData.institution === 'RSB' && formData.department !== 'PGDM') {
      setFormData(prev => ({ ...prev, department: 'PGDM', sections: [] }));
    }
  }, [formData.institution]);

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

  const fetchBatches = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/batches');
      if (response.ok) {
        const data = await response.json();
        setBatches(data);
      }
    } catch (error) {
      console.error('Failed to fetch batches:', error);
    }
  };

  const fetchClasses = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/classes');
      if (response.ok) {
        const data = await response.json();
        setClasses(data);
      }
    } catch (error) {
      console.error('Failed to fetch classes:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddSection = (e: React.FormEvent) => {
    e.preventDefault();
    if (newSection && !formData.sections.includes(newSection.toUpperCase())) {
      setFormData({
        ...formData,
        sections: [...formData.sections, newSection.toUpperCase()]
      });
      setNewSection('');
    }
  };

  const removeSection = (section: string) => {
    setFormData({
      ...formData,
      sections: formData.sections.filter(s => s !== section)
    });
  };

  const handleSave = async () => {
    if (formData.sections.length === 0) {
      showAlert('Required', 'Please add at least one section', 'error');
      return;
    }

    try {
      const response = await fetch(API_BASE_URL + '/api/classes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        fetchClasses();
        setFormData({ ...formData, sections: [] });
        showAlert('Success', 'Class mapping saved successfully.', 'success');
      }
    } catch (error) {
      console.error('Failed to save class mapping:', error);
      showAlert('Error', 'Failed to save class mapping.', 'error');
    }
  };

  const handleDelete = async (id: number) => {
    showConfirm(
      'Delete Mapping',
      'Are you sure you want to delete this mapping?',
      async () => {
        try {
          const response = await fetch(`${API_BASE_URL}/api/classes/${id}`, {
            method: 'DELETE'
          });
          if (response.ok) {
            setClasses(prev => prev.filter(c => c.id !== id));
            showAlert('Success', 'Mapping deleted successfully.', 'success');
          }
        } catch (error) {
          console.error('Delete failed:', error);
          showAlert('Error', 'Failed to delete mapping.', 'error');
        }
      }
    );
  };

  const handlePromote = async () => {
    showConfirm(
      'Academic Promotion',
      `WARNING: This action will shift all academic structures for ${formData.institution} forward:\n• 1st Year → 2nd Year\n• 2nd Year → 3rd Year\n• 3rd Year → 4th Year\n• 4th Year mappings will be PERMANENTLY DELETED.\n\nDo you wish to proceed?`,
      async () => {
        try {
          const response = await fetch(`${API_BASE_URL}/api/classes/promote?institution=${formData.institution}`, {
            method: 'POST'
          });
          if (response.ok) {
            fetchClasses();
            showAlert('Success', `${formData.institution} academic year promotion completed successfully!`, 'success');
          }
        } catch (error) {
          console.error('Promotion failed:', error);
          showAlert('Error', 'Promotion failed.', 'error');
        }
      }
    );
  };

  const handleCreateTempBatch = () => {
    if (!newBatchName.trim()) {
      showAlert('Required', 'Please enter a batch name', 'error');
      return;
    }
    const newBatch = {
      id: Date.now() + Math.floor(Math.random() * 1000),
      name: newBatchName.trim(),
      department: selectedBatchDept,
      classes: []
    };
    setTempBatches([...tempBatches, newBatch]);
    setNewBatchName('');
  };

  const handleDeleteTempBatch = (batchId: number) => {
    setTempBatches(tempBatches.filter(b => b.id !== batchId));
  };

  const handleToggleClassInTempBatch = (batchId: number, classStr: string) => {
    setTempBatches(tempBatches.map(b => {
      if (b.id !== batchId) return b;
      const isAssigned = b.classes?.includes(classStr);
      return {
        ...b,
        classes: isAssigned
          ? b.classes.filter((c: string) => c !== classStr)
          : [...(b.classes || []), classStr]
      };
    }));
  };

  const handleSaveChanges = async () => {
    try {
      const originalDeptBatches = batches.filter(b => b.department === selectedBatchDept);
      
      // 1. Identify deleted batches (in original but not in temp)
      const deletedBatches = originalDeptBatches.filter(ob => !tempBatches.some(tb => String(tb.id) === String(ob.id)));
      
      // 2. Perform deletes
      for (const db of deletedBatches) {
        await fetch(`${API_BASE_URL}/api/batches/${db.id}`, { method: 'DELETE' });
      }
      
      // 3. Save / Update current batches in tempBatches
      for (const tb of tempBatches) {
        await fetch(API_BASE_URL + '/api/batches', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: tb.id,
            name: tb.name,
            department: tb.department,
            classes: tb.classes
          })
        });
      }
      
      // 4. Refresh state
      await fetchBatches();
      showAlert('Success', 'Batch configurations saved successfully.', 'success');
    } catch (error) {
      console.error('Failed to save batch changes:', error);
      showAlert('Error', 'Failed to save changes.', 'error');
    }
  };

  const filteredClasses = classes
    .filter(c => 
      c.institution === formData.institution && (
        c.department.toLowerCase().includes(searchTerm.toLowerCase()) ||
        c.academicYear.toLowerCase().includes(searchTerm.toLowerCase())
      )
    )
    .sort((a, b) => b.id - a.id);

  const currentClasses = filteredClasses.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const selectedDeptClasses = classes.filter(c => c.institution === formData.institution && c.department === formData.department);
  const totalClassesCount = selectedDeptClasses.reduce((sum, c) => sum + c.sections.length, 0);
  const hasMoreThanFourClasses = totalClassesCount > 4;
  const deptClassesList = selectedDeptClasses.flatMap(c => c.sections.map(sec => `${c.academicYear} - ${sec}`));

  const selectedBatchDeptClasses = classes.filter(c => c.department === selectedBatchDept);
  const batchDeptClassesList = selectedBatchDeptClasses.flatMap(c => c.sections.map(sec => `${c.academicYear} - ${sec}`));

  return (
    <div className="space-y-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
        <div>
          <h1 className="text-4xl font-black text-text-dark tracking-tight mb-1">Class Management</h1>
          <p className="text-text-muted font-black uppercase tracking-widest text-[10px]">Define institutional academic structures & sections</p>
        </div>
        
        <div className="flex items-center gap-4">
          <button 
            onClick={handlePromote}
            className="flex items-center gap-3 bg-[#FFF9ED] text-[#D97706] border border-[#FDE68A] px-6 py-3 rounded-2xl font-black text-[11px] uppercase tracking-widest hover:scale-105 transition-all"
          >
            <RefreshCw className="w-4 h-4" />
            Promote Academic Year
            <AlertTriangle className="w-4 h-4" />
          </button>
          <div className="w-12 h-12 bg-brand-glow rounded-2xl flex items-center justify-center text-brand-indigo premium-shadow">
            <Building2 className="w-6 h-6" />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
        {/* Left Column - Form */}
        <div className="lg:col-span-4">
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow p-8 space-y-8 sticky top-10"
          >
            <div className="flex items-center gap-4">
              <div className="w-10 h-10 bg-brand-indigo rounded-xl flex items-center justify-center text-white">
                <Plus className="w-6 h-6" />
              </div>
              <h2 className="text-xl font-black text-text-dark tracking-tight">Add New Mapping</h2>
            </div>

            <div className="space-y-6">
              {/* Institution */}
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Select Institution</label>
                <div className="flex gap-4">
                  {[
                    { id: 'RIT', logo: ritLogo, label: 'RIT' },
                    { id: 'RSB', logo: rsbLogo, label: 'RSB' }
                  ].map(inst => (
                    <button
                      key={inst.id}
                      type="button"
                      onClick={() => setFormData({...formData, institution: inst.id})}
                      className={cn(
                        "flex-1 h-20 rounded-2xl transition-all border-2 flex items-center justify-center relative overflow-hidden group",
                        formData.institution === inst.id 
                          ? "bg-white border-brand-indigo premium-shadow" 
                          : "bg-slate-50 border-transparent grayscale opacity-50 hover:opacity-100 hover:grayscale-0 hover:bg-white hover:border-slate-200"
                      )}
                    >
                      <img 
                        src={inst.logo} 
                        alt={inst.label} 
                        className={cn(
                          "transition-all",
                          inst.id === 'RIT' ? "h-10" : "h-7"
                        )}
                      />
                    </button>
                  ))}
                </div>
              </div>

              {/* Department */}
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Department</label>
                <select 
                  value={formData.department}
                  onChange={e => setFormData({...formData, department: e.target.value})}
                  className="w-full bg-slate-50 border-transparent rounded-2xl py-4 px-6 text-sm font-bold focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                >
                  {currentDepartments.map(dept => <option key={dept} value={dept}>{dept}</option>)}
                </select>
              </div>

              {/* Academic Year */}
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Academic Year</label>
                <select 
                  value={formData.academicYear}
                  onChange={e => setFormData({...formData, academicYear: e.target.value})}
                  className="w-full bg-slate-50 border-transparent rounded-2xl py-4 px-6 text-sm font-bold focus:bg-white focus:border-brand-indigo transition-all appearance-none"
                >
                  {years.map(year => <option key={year} value={year}>{year}</option>)}
                </select>
              </div>

              {/* Sections */}
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Sections</label>
                <div className="bg-slate-50 rounded-2xl p-4 space-y-4">
                  <div className="flex flex-wrap gap-2">
                    <AnimatePresence>
                      {formData.sections.map(section => (
                        <motion.span
                          key={section}
                          initial={{ scale: 0.8, opacity: 0 }}
                          animate={{ scale: 1, opacity: 1 }}
                          exit={{ scale: 0.8, opacity: 0 }}
                          className="px-3 py-1.5 bg-white rounded-lg text-xs font-black text-brand-indigo border border-brand-indigo/10 flex items-center gap-2 group"
                        >
                          {section}
                          <button onClick={() => removeSection(section)} className="hover:text-status-danger transition-colors">
                            <X className="w-3 h-3" />
                          </button>
                        </motion.span>
                      ))}
                    </AnimatePresence>
                  </div>
                  <form onSubmit={handleAddSection} className="flex gap-2">
                    <input 
                      type="text"
                      placeholder="Type section (eg. A)..."
                      value={newSection}
                      onChange={e => setNewSection(e.target.value)}
                      className="flex-1 bg-transparent border-none text-xs font-bold focus:ring-0 p-0"
                    />
                    <button type="submit" className="w-8 h-8 bg-brand-glow rounded-lg flex items-center justify-center text-brand-indigo hover:bg-brand-indigo hover:text-white transition-all">
                      <Plus className="w-4 h-4" />
                    </button>
                  </form>
                </div>
              </div>

              <button 
                onClick={handleSave}
                className="w-full bg-brand-indigo text-white rounded-2xl py-5 font-black text-[12px] uppercase tracking-[0.2em] premium-shadow hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-3"
              >
                <Layers className="w-5 h-5" />
                Save Configuration
              </button>
            </div>
          </motion.div>
        </div>

        {/* Right Column - Table */}
        <div className="lg:col-span-8">
          <motion.div 
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden"
          >
            <div className="p-8 border-b border-slate-50 flex items-center justify-between gap-6">
              <div className="flex items-center gap-4">
                <div className="w-2 h-8 bg-brand-indigo rounded-full" />
                <h3 className="text-xl font-black text-text-dark tracking-tight">Academic Structure</h3>
              </div>
              
              <div className="relative flex-1 max-w-xs">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                <input 
                  type="text"
                  placeholder="Search structures..."
                  value={searchTerm}
                  onChange={e => setSearchTerm(e.target.value)}
                  className="w-full bg-slate-50 border-transparent rounded-2xl py-3 pl-12 pr-4 text-sm font-bold focus:bg-white focus:border-brand-indigo transition-all"
                />
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-slate-50/50">
                    <th className="px-8 py-5 text-[9px] font-black uppercase tracking-[0.2em] text-text-muted">Institution</th>
                    <th className="px-8 py-5 text-[9px] font-black uppercase tracking-[0.2em] text-text-muted">Department \ Year</th>
                    <th className="px-8 py-5 text-[9px] font-black uppercase tracking-[0.2em] text-text-muted">Configured Sections</th>
                    <th className="px-8 py-5 text-[9px] font-black uppercase tracking-[0.2em] text-text-muted text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {isLoading ? (
                    <tr><td colSpan={4} className="p-20 text-center text-text-muted italic">Loading structure...</td></tr>
                  ) : filteredClasses.length === 0 ? (
                    <tr><td colSpan={4} className="p-20 text-center text-text-muted italic">No academic structures defined.</td></tr>
                  ) : (
                    currentClasses.map((item, idx) => (
                      <motion.tr 
                        key={item.id}
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: idx * 0.05 }}
                        className="group hover:bg-slate-50/30 transition-colors"
                      >
                        <td className="px-8 py-6">
                          <div className="w-16 h-10 bg-slate-50 rounded-xl border border-slate-100 flex items-center justify-center p-1.5">
                            <img 
                              src={item.institution === 'RIT' ? ritLogo : rsbLogo} 
                              alt={item.institution}
                              className="h-full object-contain"
                            />
                          </div>
                        </td>
                        <td className="px-8 py-6">
                          <div className="flex items-center gap-5">
                            <div className="w-12 h-12 rounded-2xl bg-slate-50 border border-slate-100 flex flex-col items-center justify-center">
                              <span className="text-[9px] font-black text-text-muted uppercase">{item.department.substring(0, 3)}</span>
                              <div className="w-4 h-0.5 bg-brand-indigo/30 rounded-full mt-0.5" />
                            </div>
                            <div>
                              <h4 className="text-sm font-black text-text-dark">{item.department}</h4>
                              <div className="flex items-center gap-1.5 text-[10px] font-black uppercase tracking-widest text-brand-indigo mt-0.5">
                                <GraduationCap className="w-3.5 h-3.5" />
                                {item.academicYear}
                              </div>
                            </div>
                          </div>
                        </td>
                        <td className="px-8 py-6">
                          <div className="flex items-center gap-2">
                            {item.sections.map(section => (
                              <span key={section} className="w-7 h-7 rounded-lg bg-white border border-slate-200 flex items-center justify-center text-[10px] font-black text-text-muted group-hover:border-brand-indigo group-hover:text-brand-indigo transition-all">
                                {section}
                              </span>
                            ))}
                            <div className="ml-4 flex items-center gap-1.5 px-3 py-1 bg-emerald-50 text-status-success rounded-lg border border-emerald-100/50">
                              <CheckCircle2 className="w-3.5 h-3.5" />
                              <span className="text-[10px] font-black uppercase tracking-widest">Ready</span>
                            </div>
                          </div>
                        </td>
                        <td className="px-8 py-6 text-right">
                          <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-all">
                            <button className="p-2.5 bg-white border border-slate-200 rounded-xl text-slate-400 hover:text-brand-indigo hover:border-brand-indigo premium-shadow-sm transition-all">
                              <Layers className="w-4.5 h-4.5" />
                            </button>
                            <button onClick={() => handleDelete(item.id)} className="p-2.5 bg-white border border-slate-200 rounded-xl text-slate-400 hover:text-status-danger hover:border-status-danger premium-shadow-sm transition-all">
                              <Trash2 className="w-4.5 h-4.5" />
                            </button>
                          </div>
                        </td>
                      </motion.tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            
            <Pagination 
              currentPage={currentPage}
              totalItems={filteredClasses.length}
              itemsPerPage={itemsPerPage}
              onPageChange={setCurrentPage}
              onItemsPerPageChange={(val) => {
                setItemsPerPage(val);
                setCurrentPage(1);
              }}
              itemsPerPageOptions={[5, 10, 20, 50]}
            />
          </motion.div>
        </div>
      </div>

      {/* Batches Section - Always Visible */}
      <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow p-8 space-y-6 mt-10">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between border-b border-slate-50 pb-6 gap-6">
          <div className="flex items-center gap-4">
            <div className="w-10 h-10 bg-brand-indigo rounded-xl flex items-center justify-center text-white">
              <Layers className="w-5 h-5" />
            </div>
            <div>
              <h3 className="text-xl font-black text-text-dark tracking-tight">Department Batches</h3>
              <p className="text-xs text-text-muted font-bold">Configure custom student batches for auditing & event planning.</p>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-4">
            {/* Select Department */}
            <div className="flex items-center gap-2">
              <span className="text-[9px] font-black text-text-muted uppercase tracking-wider">Department:</span>
              <select 
                value={selectedBatchDept}
                onChange={e => setSelectedBatchDept(e.target.value)}
                className="bg-slate-50 border border-slate-200 rounded-xl py-2 px-3 text-xs font-bold focus:bg-white focus:border-brand-indigo outline-none transition-all text-slate-800 cursor-pointer"
              >
                {ritDepartments.filter(d => d !== 'Club' && d !== 'Centre' && d !== 'Placement Department').map(dept => (
                  <option key={dept} value={dept}>{dept}</option>
                ))}
              </select>
            </div>

            {/* Create Batch Form */}
            <div className="flex items-center gap-2">
              <input 
                type="text" 
                placeholder="New Batch Name (e.g. Batch 1)"
                value={newBatchName}
                onChange={e => setNewBatchName(e.target.value)}
                className="bg-slate-50 border border-slate-200 rounded-xl py-2 px-4 text-xs font-bold focus:bg-white focus:border-brand-indigo outline-none transition-all text-slate-800"
              />
              <button
                onClick={handleCreateTempBatch}
                className="px-4 py-2 bg-brand-indigo text-white rounded-xl font-black text-[10px] uppercase tracking-widest hover:scale-[1.02] active:scale-[0.98] transition-all"
              >
                Create
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {tempBatches.map(batch => (
            <div key={batch.id} className="bg-slate-50 p-6 rounded-3xl border border-slate-100 space-y-4">
              <div className="flex items-center justify-between border-b border-slate-200 pb-2">
                <span className="text-sm font-black text-brand-navy uppercase">{batch.name}</span>
                <button 
                  onClick={() => handleDeleteTempBatch(batch.id)}
                  className="text-[10px] font-black text-rose-500 hover:text-rose-700 uppercase tracking-widest transition-all"
                >
                  Delete
                </button>
              </div>

              <div className="space-y-3">
                <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest">Assign Classes to this Batch:</span>
                {batchDeptClassesList.length > 0 ? (
                  <div className="grid grid-cols-2 gap-3">
                    {batchDeptClassesList.map(cls => {
                      const isChecked = batch.classes?.includes(cls);
                      const isAssignedElsewhere = tempBatches.some(other => other.id !== batch.id && other.classes?.includes(cls));
                      if (isAssignedElsewhere) return null;
                      return (
                        <label key={cls} className="flex items-center gap-2 bg-white p-3 rounded-xl border border-slate-200 hover:border-brand-indigo/30 transition-all cursor-pointer">
                          <input 
                            type="checkbox"
                            checked={isChecked}
                            onChange={() => handleToggleClassInTempBatch(batch.id, cls)}
                            className="w-4 h-4 rounded border-slate-300 text-brand-indigo focus:ring-brand-indigo cursor-pointer"
                          />
                          <span className="text-[10px] font-black text-slate-600 uppercase tracking-tight">{cls}</span>
                        </label>
                      );
                    })}
                  </div>
                ) : (
                  <span className="block text-[10px] font-bold text-text-muted italic">No classes configured for {selectedBatchDept}.</span>
                )}
              </div>
            </div>
          ))}
          {tempBatches.length === 0 && (
            <div className="col-span-2 py-12 text-center text-slate-400 font-bold uppercase tracking-wider text-xs border-2 border-dashed border-slate-200 rounded-[2rem]">
              No batches created yet for {selectedBatchDept}. Use the form above to add your first batch.
            </div>
          )}
        </div>

        {tempBatches.length > 0 && (
          <div className="flex items-center justify-end border-t border-slate-100 pt-6 mt-6">
            <button
              onClick={handleSaveChanges}
              className="px-6 py-3 bg-emerald-500 hover:bg-emerald-600 text-white rounded-xl font-black text-[10px] uppercase tracking-widest hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center gap-2 shadow-md shadow-emerald-500/10"
            >
              <CheckCircle2 className="w-4 h-4" />
              Save Changes
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
