import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Search, Briefcase, X, Users, Calendar, User, Building2, Tag, ArrowRight } from 'lucide-react';
import axios from 'axios';
import toast from 'react-hot-toast';
import useAuthStore from '../../store/authStore';
import DepartmentModal from '../../components/DepartmentModal';

const fmtD = d => d ? new Date(d).toLocaleDateString('en-GB', { day:'2-digit', month:'short', year:'numeric' }) : '—';

const STATUS_EMP = {
  active:     'bg-green-100 text-green-700',
  inactive:   'bg-gray-100 text-gray-600',
  terminated: 'bg-red-100 text-red-700',
  resigned:   'bg-red-100 text-red-700',
  'on-leave': 'bg-amber-100 text-amber-700',
};

export default function Departments() {
  const navigate = useNavigate();
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading]         = useState(true);
  const [search, setSearch]           = useState('');
  const [staffSearch, setStaffSearch] = useState('');
  const [showModal, setShowModal]     = useState(false);
  const [detail, setDetail]           = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const { user } = useAuthStore();

  useEffect(() => { fetchDepartments(); }, [search]);

  const fetchDepartments = async () => {
    try {
      const response = await axios.get('/api/departments', { params: { search, per_page: 50 } });
      setDepartments(response.data.data || response.data);
    } catch { toast.error('Failed to fetch departments'); }
    finally { setLoading(false); }
  };

  const openDetail = async (dept) => {
    setDetail({ ...dept, employees: dept.employees || [] });
    setDetailLoading(true);
    try {
      const res = await axios.get(`/api/departments/${dept.id}`);
      setDetail(res.data.department || res.data);
    } catch { toast.error('Failed to load department details'); }
    finally { setDetailLoading(false); }
  };

  const handleDelete = async (id, e) => {
    e.stopPropagation();
    if (!confirm('Are you sure you want to delete this department?')) return;
    try {
      await axios.delete(`/api/departments/${id}`);
      toast.success('Department deleted successfully');
      fetchDepartments();
      if (detail?.id === id) setDetail(null);
    } catch { toast.error('Failed to delete department'); }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="w-10 h-10 rounded-full border-4 border-t-transparent border-primary-600 animate-spin"/>
      </div>
    );
  }

  return (
    <div className="space-y-6 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Departments</h1>
          <p className="text-gray-600 mt-1">Click any department to view its full details and team</p>
        </div>
        <button onClick={() => setShowModal(true)} className="btn-primary flex items-center">
          <Plus className="w-5 h-5 mr-2" /> Add Department
        </button>
      </div>

      <div className="card">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input type="text" value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search departments..." className="input-field pl-10"/>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {departments.map(dept => (
          <div key={dept.id} className="card hover:shadow-lg transition-shadow cursor-pointer"
            onClick={() => openDetail(dept)}>
            <div className="flex items-start justify-between mb-4">
              <div className="flex items-center space-x-3">
                <div className="w-12 h-12 bg-primary-100 rounded-lg flex items-center justify-center">
                  <Briefcase className="w-6 h-6 text-primary-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">{dept.name}</h3>
                  {dept.code && <p className="text-sm text-gray-500">{dept.code}</p>}
                </div>
              </div>
              <span className={`px-2 py-1 text-xs font-medium rounded-full ${dept.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}`}>
                {dept.status}
              </span>
            </div>

            {dept.description && (
              <p className="text-sm text-gray-600 mb-4 line-clamp-2">{dept.description}</p>
            )}

            <div className="space-y-2 mb-4">
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">Manager:</span>
                <span className="font-medium text-gray-900">{dept.manager?.name || 'Not assigned'}</span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">Staff:</span>
                <span className="font-medium text-primary-600">{dept.employee_count || (dept.employees?.length || 0)}</span>
              </div>
              {dept.created_at && (
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600">Created:</span>
                  <span className="text-gray-500">{fmtD(dept.created_at)}</span>
                </div>
              )}
            </div>

            <div className="flex items-center space-x-2 pt-4 border-t border-gray-100">
              <button className="flex-1 px-4 py-2 bg-primary-50 hover:bg-primary-100 text-primary-700 rounded-lg text-sm font-medium transition-colors">
                View Details
              </button>
              <button onClick={e => handleDelete(dept.id, e)}
                className="px-4 py-2 text-red-600 hover:bg-red-50 rounded-lg text-sm font-medium transition-colors">
                Delete
              </button>
            </div>
          </div>
        ))}
      </div>

      {departments.length === 0 && (
        <div className="text-center py-12">
          <Briefcase className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No departments found</h3>
          <p className="text-gray-600">{search ? 'Try adjusting your search' : 'Get started by adding a new department'}</p>
        </div>
      )}

      {showModal && (
        <DepartmentModal onClose={() => setShowModal(false)} onSuccess={() => { setShowModal(false); fetchDepartments(); }}/>
      )}

      {/* ── Department Detail Modal ─────────────────────────────── */}
      {detail && (
        <div className="fixed inset-0 z-50 flex items-start justify-center p-4 bg-black/50 overflow-y-auto" onClick={()=>setDetail(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl my-6" onClick={e=>e.stopPropagation()}>

            {/* Header */}
            <div className="p-6 rounded-t-2xl bg-gradient-to-r from-primary-700 to-primary-500">
              <div className="flex items-start justify-between mb-1">
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-2xl bg-white/20 flex items-center justify-center">
                    <Briefcase size={28} className="text-white"/>
                  </div>
                  <div>
                    <h2 className="text-xl font-black text-white">{detail.name}</h2>
                    {detail.code && <p className="text-primary-200 text-sm">Code: {detail.code}</p>}
                    <span className={`mt-1 inline-block text-xs font-semibold px-2 py-0.5 rounded-full ${detail.status === 'active' ? 'bg-green-400/30 text-green-100' : 'bg-gray-400/30 text-gray-100'}`}>
                      {detail.status}
                    </span>
                  </div>
                </div>
                <button onClick={()=>setDetail(null)} className="text-white/70 hover:text-white mt-1"><X size={20}/></button>
              </div>
            </div>

            <div className="p-6 space-y-5">
              {/* About */}
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">About this Department</p>
                {detail.description ? (
                  <p className="text-gray-700 text-sm leading-relaxed">{detail.description}</p>
                ) : (
                  <p className="text-gray-400 text-sm italic">No description provided.</p>
                )}
              </div>

              {/* Key facts */}
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                {[
                  { icon: User,        label:'Manager',      value: detail.manager?.name || 'Not assigned' },
                  { icon: Calendar,   label:'Created',       value: fmtD(detail.created_at) },
                  { icon: Users,      label:'Total Staff',   value: (detail.employees?.length || detail.employee_count || 0) + ' people' },
                  { icon: Building2,  label:'Company',       value: detail.company?.name || '—' },
                  { icon: Tag,        label:'Cost Centre',   value: detail.cost_center || '—' },
                  { icon: Briefcase,  label:'Budget',        value: detail.budget ? `\u20A6${Number(detail.budget).toLocaleString()}` : '—' },
                ].map((r,i) => (
                  <div key={i} className="bg-gray-50 rounded-xl p-3">
                    <div className="flex items-center gap-1.5 mb-1">
                      <r.icon size={13} className="text-gray-400"/>
                      <p className="text-xs text-gray-400 font-medium">{r.label}</p>
                    </div>
                    <p className="text-sm font-bold text-gray-800">{r.value}</p>
                  </div>
                ))}
              </div>

              {/* Staff list */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">
                    Staff Members {detail.employees?.length > 0 && `(${detail.employees.length})`}
                  </p>
                </div>
                {/* Staff search */}
                {detail.employees?.length > 0 && (
                  <div className="relative mb-3">
                    <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"/>
                    <input value={staffSearch} onChange={e=>setStaffSearch(e.target.value)}
                      placeholder="Search staff by name or position…"
                      className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-primary-400"/>
                  </div>
                )}
                {detailLoading ? (
                  <div className="flex justify-center py-6"><div className="w-8 h-8 rounded-full border-4 border-t-transparent border-primary-600 animate-spin"/></div>
                ) : !detail.employees || detail.employees.length === 0 ? (
                  <p className="text-gray-400 text-sm text-center py-6">No staff in this department yet</p>
                ) : (
                  <div className="space-y-2 max-h-72 overflow-y-auto">
                    {detail.employees
                      .filter(emp => {
                        if (!staffSearch) return true;
                        const q = staffSearch.toLowerCase();
                        return (`${emp.first_name} ${emp.last_name}`).toLowerCase().includes(q)
                          || (emp.position||'').toLowerCase().includes(q)
                          || (emp.job_title||'').toLowerCase().includes(q);
                      })
                      .map(emp => (
                      <button key={emp.id} onClick={()=>{ setDetail(null); navigate(`/employees/${emp.id}`); }}
                        className="w-full flex items-center justify-between bg-gray-50 rounded-xl px-4 py-3 hover:bg-primary-50 hover:shadow-sm transition-all cursor-pointer text-left">
                        <div className="flex items-center gap-3">
                          <div className="w-9 h-9 rounded-full bg-primary-100 flex items-center justify-center font-bold text-primary-600 text-sm flex-shrink-0">
                            {(emp.first_name?.[0] || '') + (emp.last_name?.[0] || '')}
                          </div>
                          <div>
                            <p className="text-sm font-semibold text-gray-900">{emp.first_name} {emp.last_name}</p>
                            <p className="text-xs text-gray-500">{emp.job_title || emp.position || 'Staff'}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-3">
                          <div className="text-right">
                            <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${STATUS_EMP[emp.status] || 'bg-gray-100 text-gray-600'}`}>
                              {(emp.status || 'active').replace('-',' ')}
                            </span>
                            <p className="text-xs text-gray-400 mt-0.5">Since {fmtD(emp.hire_date)}</p>
                          </div>
                          <ArrowRight size={14} className="text-gray-400 flex-shrink-0"/>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
