import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal, ModalBody } from '../../components/ui/Modal';
import {
  AlertCircle, CheckCircle2, XCircle, X, Loader2,
  Calendar, User, ChevronLeft, ChevronRight, Search, RefreshCw,
} from 'lucide-react';
import { useHRStore, LeaveRequest } from '../../store/hr';

const PAGE_SIZE = 20;

const statusBadge = (status: string) => {
  const s = status.toLowerCase();
  if (s === 'approved') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (s === 'rejected') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  if (s === 'pending') return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
  return 'bg-muted text-text-muted border-border';
};

const fmtDate = (d?: string) => {
  if (!d) return '—';
  const dt = new Date(d);
  return Number.isNaN(dt.getTime()) ? d : dt.toLocaleDateString();
};

export default function LeaveApproval() {
  const navigate = useNavigate();
  const {
    leaveRequests,
    fetchLeaveRequests,
    updateLeaveStatus,
    error,
  } = useHRStore();

  const [status, setStatus] = useState<'pending' | 'approved' | 'rejected' | ''>('pending');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [busy, setBusy] = useState<string | null>(null);
  const [rejecting, setRejecting] = useState<LeaveRequest | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);

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

  const filtered = useMemo(() => {
    return leaveRequests.filter((lr) => {
      if (status && lr.status !== status) return false;
      if (!search.trim()) return true;
      const needle = search.toLowerCase();
      return (
        (lr.first_name || '').toLowerCase().includes(needle) ||
        (lr.last_name || '').toLowerCase().includes(needle) ||
        (lr.leave_type || '').toLowerCase().includes(needle) ||
        (lr.reason || '').toLowerCase().includes(needle)
      );
    });
  }, [leaveRequests, status, search]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const onApprove = async (lr: LeaveRequest) => {
    setBusy(lr.uid);
    setBanner(null);
    try {
      await updateLeaveStatus(lr.uid, 'approved');
      setBanner({ kind: 'ok', msg: `Approved leave request for ${lr.first_name || ''} ${lr.last_name || ''}.` });
    } catch (e: any) {
      setBanner({ kind: 'err', msg: e?.response?.data?.error || e?.message || 'Failed to approve leave request.' });
    } finally {
      setBusy(null);
    }
  };

  const openReject = (lr: LeaveRequest) => {
    setRejecting(lr);
    setRejectReason(lr.rejection_reason || '');
    setBanner(null);
  };

  const confirmReject = async () => {
    if (!rejecting) return;
    const reason = rejectReason.trim();
    if (!reason) {
      setBanner({ kind: 'err', msg: 'A rejection reason is required.' });
      return;
    }
    setBusy(rejecting.uid);
    try {
      await updateLeaveStatus(rejecting.uid, 'rejected', reason);
      setBanner({ kind: 'ok', msg: `Rejected leave request for ${rejecting.first_name || ''} ${rejecting.last_name || ''}.` });
      setRejecting(null);
      setRejectReason('');
    } catch (e: any) {
      setBanner({ kind: 'err', msg: e?.response?.data?.error || e?.message || 'Failed to reject leave request.' });
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Leave Approval</h1>
          <p className="text-text-muted mt-1 text-lg">
            Review and act on staff leave requests.
          </p>
        </div>
        <button
          onClick={() => fetchLeaveRequests()}
          className="flex items-center gap-2 px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
        >
          <RefreshCw size={16} /> Refresh
        </button>
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="relative">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search name, type, or reason…"
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(0); }}
              className="w-full pl-9 pr-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>
          <select
            value={status}
            onChange={(e) => { setStatus(e.target.value as any); setPage(0); }}
            className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
          >
            <option value="">All statuses</option>
            <option value="pending">Pending</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
            <option value="cancelled">Cancelled</option>
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">
          {filtered.length} request{filtered.length === 1 ? '' : 's'}
          {status && ` · status = ${status}`}
          {search.trim() && ` · matching "${search.trim()}"`}
        </p>
      </div>

      {banner && (
        <div
          className={`rounded-2xl border p-4 flex items-center gap-3 text-sm ${
            banner.kind === 'ok'
              ? 'bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/30 dark:border-emerald-900 dark:text-emerald-300'
              : 'bg-red-50 border-red-200 text-red-700 dark:bg-red-950/30 dark:border-red-900 dark:text-red-300'
          }`}
        >
          {banner.kind === 'ok' ? <CheckCircle2 size={18} /> : <AlertCircle size={18} />}
          <span className="flex-1">{banner.msg}</span>
          <button onClick={() => setBanner(null)} className="text-xs font-bold underline">
            Dismiss
          </button>
        </div>
      )}

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </div>
      )}

      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Staff
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Type
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Dates
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Days
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Status
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((lr) => {
                  const isBusy = busy === lr.uid;
                  const name = [lr.first_name, lr.last_name].filter(Boolean).join(' ') || `Staff #${lr.staff_id}`;
                  return (
                    <tr key={lr.uid} className="hover:bg-muted/40 transition-colors">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <div className="p-1.5 rounded-md bg-muted text-text-muted">
                            <User size={14} />
                          </div>
                          <div>
                            <p className="text-[0.85rem] font-semibold text-text">{name}</p>
                            <p className="text-[0.65rem] text-text-muted line-clamp-1">{lr.reason || 'No reason given'}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 text-[0.85rem] text-text-secondary">
                        {lr.leave_type}
                      </td>
                      <td className="px-6 py-4 text-[0.75rem] font-mono text-text-muted whitespace-nowrap">
                        <span className="inline-flex items-center gap-1">
                          <Calendar size={12} />
                          {fmtDate(lr.start_date)} → {fmtDate(lr.end_date)}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-[0.85rem] font-bold text-text">
                        {lr.days_count ?? '—'}
                      </td>
                      <td className="px-6 py-4">
                        <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusBadge(lr.status)}`}>
                          {lr.status}
                        </span>
                        {lr.rejection_reason && (
                          <p className="text-[0.65rem] text-text-muted italic mt-1 line-clamp-2">
                            {lr.rejection_reason}
                          </p>
                        )}
                      </td>
                      <td className="px-6 py-4 text-right whitespace-nowrap">
                        <div className="inline-flex items-center gap-1">
                          {lr.status === 'pending' ? (
                            <>
                              <button
                                onClick={() => onApprove(lr)}
                                disabled={isBusy}
                                className="p-2 rounded-lg hover:bg-emerald-500 hover:text-white text-emerald-600 disabled:opacity-40 transition-all"
                                title="Approve request"
                                aria-label="Approve request"
                              >
                                {isBusy ? <Loader2 size={16} className="animate-spin" /> : <CheckCircle2 size={16} />}
                              </button>
                              <button
                                onClick={() => openReject(lr)}
                                disabled={isBusy}
                                className="p-2 rounded-lg hover:bg-rose-500 hover:text-white text-rose-500 disabled:opacity-40 transition-all"
                                title="Reject request"
                                aria-label="Reject request"
                              >
                                <XCircle size={16} />
                              </button>
                            </>
                          ) : (
                            <span className="text-[0.65rem] text-text-muted italic">No actions</span>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={6} className="px-6 py-10 text-center text-text-muted text-sm">
                    No leave requests match the current filters.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">
            Page {page + 1} of {totalPages}
          </span>
          <div className="inline-flex items-center gap-2">
            <button
              disabled={page === 0}
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all"
            >
              <ChevronLeft size={14} /> Prev
            </button>
            <button
              disabled={page + 1 >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all"
            >
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      <div className="text-[0.65rem] text-text-muted italic text-center">
        Need to dig deeper? Visit the legacy <button onClick={() => navigate('/hr/management')} className="underline font-bold">HR Center</button>.
      </div>

      {rejecting && (
        <Modal
          open={true}
          onClose={() => setRejecting(null)}
          title="Reject leave request"
          icon={XCircle}
          maxWidth="max-w-md"
          zIndex={110}
        >
          <ModalBody className="p-6">
            <p className="text-sm text-text-muted mb-3">
              {rejecting.leave_type} · {fmtDate(rejecting.start_date)} → {fmtDate(rejecting.end_date)}
              {' '}for {rejecting.first_name || ''} {rejecting.last_name || ''}.
            </p>
            <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">
              Reason (required)
            </label>
            <textarea
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              rows={3}
              maxLength={500}
              placeholder="Why is this being rejected?"
              className="w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
            <p className="text-[0.65rem] text-text-muted mt-1">
              {rejectReason.trim().length}/500 characters
            </p>
            <div className="mt-5 flex justify-end gap-2">
              <button
                onClick={() => { setRejecting(null); setRejectReason(''); }}
                disabled={busy === rejecting.uid}
                className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
              >
                Cancel
              </button>
              <button
                onClick={confirmReject}
                disabled={busy === rejecting.uid || !rejectReason.trim()}
                className="flex items-center gap-2 px-4 py-2 rounded-xl bg-rose-500 text-white text-sm font-bold hover:bg-rose-600 disabled:opacity-40 transition-all"
              >
                {busy === rejecting.uid ? <Loader2 size={14} className="animate-spin" /> : <XCircle size={14} />}
                <span>Reject request</span>
              </button>
            </div>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}