'use client';
import { useState } from 'react';
import HOSLayout from '../../../components/HOSLayout';
import { useAuth } from '../../../lib/authContext';
import { useLeaveStore } from '../../../lib/leaveStore';
import { LEAVE_POLICIES } from '../../hr/leave/leaveData';
import { downloadLeaveComputationForm } from '../../../lib/leaveComputationForm';

const BRAND = '#B22698';

const STATUS_CONFIG: Record<string, { color: string; bg: string; icon: string }> = {
  'HOD Approved': { color: '#2563eb', bg: '#dbeafe', icon: 'ri-shield-check-line' },
  'Pending Review': { color: '#7c3aed', bg: '#ede9fe', icon: 'ri-refresh-line' },
  'HOS Approved': { color: BRAND, bg: '#fce7f3', icon: 'ri-check-double-line' },
  Approved: { color: '#16a34a', bg: '#dcfce7', icon: 'ri-checkbox-circle-line' },
  Rejected: { color: '#dc2626', bg: '#fee2e2', icon: 'ri-close-circle-line' },
  Pending: { color: '#d97706', bg: '#fef3c7', icon: 'ri-time-line' },
  Cancelled: { color: '#6b7280', bg: '#f3f4f6', icon: 'ri-forbid-line' },
};

type TabType = 'pending' | 'hod_approved' | 'hos_approved';

export default function HOSRequestsPage() {
  const { user } = useAuth();
  const { requests, updateRequests } = useLeaveStore();
  const [toast, setToast] = useState('');
  const [rejectModal, setRejectModal] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [commentModal, setCommentModal] = useState<string | null>(null);
  const [forwardComment, setForwardComment] = useState('');
  const [tab, setTab] = useState<TabType>('pending');
  const [search, setSearch] = useState('');
  const [deptFilter, setDeptFilter] = useState('All');

  if (!user) return null;

  const showToast = (msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(''), 3500);
  };

  const hosUserId = user.employeeId || user.id;
  const hosName = user.name;

  // Fixed: Removed the incorrect comparison with 'Pending Review'
  const pendingRequests = requests.filter(
    (r) => r.status === 'HOD Approved' && r.employeeId !== hosUserId
  );
  
  const hodApprovedAll = requests.filter(
    (r) =>
      r.employeeId !== hosUserId &&
      (r.status === 'HOD Approved' ||
        r.status === 'HOS Approved' ||
        r.status === 'Approved' ||
        (r.status === 'Rejected' && (r.rejectedStage === 'HOS' || r.rejectedStage === 'HR')))
  );
  
  const hosApprovedAll = requests.filter(
    (r) =>
      r.employeeId !== hosUserId &&
      (r.status === 'HOS Approved' ||
        r.status === 'Approved' ||
        (r.status === 'Rejected' && r.rejectedStage === 'HOS'))
  );

  const getTabData = () => {
    if (tab === 'pending') return pendingRequests;
    if (tab === 'hod_approved') return hodApprovedAll;
    return hosApprovedAll;
  };

  const departments = ['All', ...Array.from(new Set(requests.map((r) => r.dept)))];

  const filtered = getTabData().filter((r) => {
    const fd = deptFilter === 'All' || r.dept === deptFilter;
    const fq = !search || r.employee.toLowerCase().includes(search.toLowerCase());
    return fd && fq;
  });

  const handleApproveWithComment = () => {
    if (!commentModal) return;
    updateRequests((prev) =>
      prev.map((r) =>
        r.id === commentModal && r.status === 'HOD Approved'
          ? {
              ...r,
              status: 'HOS Approved' as const,
              hosApprovedBy: `${hosName} (HOS)`,
              hosApprovedOn: new Date().toISOString().split('T')[0],
              hosComment: forwardComment || 'Confirmed and forwarded to HR',
            }
          : r
      )
    );
    setCommentModal(null);
    setForwardComment('');
    showToast('Confirmed and forwarded to HR for final approval.');
  };

  const handleReject = () => {
    if (!rejectModal || !rejectReason) return;
    updateRequests((prev) =>
      prev.map((r) =>
        r.id === rejectModal
          ? {
              ...r,
              status: 'Pending Review' as const,
              reviewRequested: true,
              reviewComment: `HOS Review Requested: ${rejectReason}`,
              reviewBy: `${hosName} (HOS)`,
              reviewDate: new Date().toISOString().split('T')[0],
              hodApprovedBy: undefined,
              hodApprovedOn: undefined,
              hosApprovedBy: undefined,
              hosApprovedOn: undefined,
            }
          : r
      )
    );
    setRejectModal(null);
    setRejectReason('');
    showToast('Review requested. Sent back to HOD and employee for changes.');
  };

  const tabs: { key: TabType; label: string; count: number }[] = [
    { key: 'pending', label: 'Pending My Review', count: pendingRequests.length },
    { key: 'hod_approved', label: 'HOD Approved (All)', count: hodApprovedAll.length },
    { key: 'hos_approved', label: 'HOS Approved / Rejected', count: hosApprovedAll.length },
  ];

  return (
    <HOSLayout title="Leave Requests Review">
      {toast && (
        <div
          className="fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2"
          style={{ background: BRAND }}
        >
          <i className="ri-checkbox-circle-line"></i>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">Leave Requests — HOS Review</h2>
            <p className="text-sm text-gray-500">Review HOD-approved requests and forward to HR with comments</p>
          </div>
          {pendingRequests.length > 0 && (
            <div className="flex items-center gap-2 bg-pink-50 border rounded-xl px-4 py-2" style={{ borderColor: BRAND }}>
              <i className="ri-alarm-warning-line" style={{ color: BRAND }}></i>
              <span className="text-sm font-semibold" style={{ color: BRAND }}>
                {pendingRequests.length} awaiting your review
              </span>
            </div>
          )}
        </div>

        <div className="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-2">
          <i className="ri-information-line text-amber-600 mt-0.5 flex-shrink-0"></i>
          <p className="text-xs text-amber-800">
            <strong>Note:</strong> Your own leave requests (as HOS) must be approved by HR directly. You cannot
            approve your own requests here. For your own leave, go to <strong>My Leave</strong> and submit — HR will
            review it.
          </p>
        </div>

        <div className="flex gap-1 bg-gray-100 rounded-xl p-1">
          {tabs.map((t) => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
              style={tab === t.key ? { background: BRAND, color: '#fff' } : { color: '#6b7280' }}
            >
              {t.label}
              {t.count > 0 && (
                <span
                  className="px-1.5 py-0.5 rounded-full text-[10px] font-bold"
                  style={
                    tab === t.key
                      ? { background: 'rgba(255,255,255,0.25)', color: '#fff' }
                      : { background: BRAND, color: '#fff' }
                  }
                >
                  {t.count}
                </span>
              )}
            </button>
          ))}
        </div>

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-gray-100 flex flex-wrap gap-3">
            <div className="relative flex-1 min-w-[180px]">
              <i className="ri-search-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search employee..."
                className="pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm w-full outline-none"
              />
            </div>
            <select
              value={deptFilter}
              onChange={(e) => setDeptFilter(e.target.value)}
              className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer"
            >
              {departments.map((d) => (
                <option key={d}>{d}</option>
              ))}
            </select>
          </div>

          {filtered.length === 0 ? (
            <div className="py-16 text-center text-gray-400">
              <i className="ri-inbox-line text-5xl block mb-3 text-gray-200"></i>
              <p>No requests for this view</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Employee</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Dept</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Leave Type</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Period</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Days</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">HOD Action</th>
                    {tab === 'hos_approved' && (
                      <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">HOS Action</th>
                    )}
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                   </tr>
                </thead>
                <tbody>
                  {filtered.map((req) => {
                    const st = STATUS_CONFIG[req.status] || STATUS_CONFIG['Pending'];
                    const policy = LEAVE_POLICIES.find((p) => p.type === req.type);
                    const showActionButtons = req.status !== 'Approved';
                    return (
                      <tr key={req.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3">
                          <div className="flex items-center gap-2">
                            <div
                              className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0"
                              style={{ background: BRAND }}
                            >
                              {req.employee.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}
                            </div>
                            <div>
                              <p className="font-medium text-gray-800">{req.employee}</p>
                              <p className="text-xs text-gray-400 font-mono">{req.id}</p>
                            </div>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-600">{req.dept}</td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-1.5">
                            <div className="w-2 h-2 rounded-full" style={{ background: policy?.color }}></div>
                            <span className="text-gray-700">{policy?.label}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-600">
                          <p>{req.startDate}</p>
                          <p className="text-gray-400">to {req.endDate}</p>
                        </td>
                        <td className="px-4 py-3 text-center font-bold text-gray-800">{req.days}</td>
                        <td className="px-4 py-3 text-xs">
                          {req.hodApprovedBy ? (
                            <div>
                              <p className="font-medium flex items-center gap-0.5" style={{ color: BRAND }}>
                                <i className="ri-check-line"></i>
                                {req.hodApprovedOn}
                              </p>
                              <p className="text-gray-400">{req.hodApprovedBy?.split('(')[0]?.trim()}</p>
                            </div>
                          ) : req.rejectedStage === 'HOD' ? (
                            <span className="text-red-600">
                              <i className="ri-close-line mr-0.5"></i>Rejected by HOD
                            </span>
                          ) : (
                            <span className="text-gray-300">—</span>
                          )}
                        </td>
                        {tab === 'hos_approved' && (
                          <td className="px-4 py-3 text-xs">
                            {req.hosApprovedBy ? (
                              <div>
                                <p className="font-medium flex items-center gap-0.5" style={{ color: BRAND }}>
                                  <i className="ri-check-double-line"></i>
                                  {req.hosApprovedOn}
                                </p>
                                <p className="text-gray-400">{req.hosApprovedBy?.split('(')[0]?.trim()}</p>
                              </div>
                            ) : req.rejectedStage === 'HOS' ? (
                              <div>
                                <span className="text-red-600">
                                  <i className="ri-close-line mr-0.5"></i>Rejected
                                </span>
                                {req.rejectionReason && (
                                  <p className="text-gray-400 text-xs mt-0.5">{req.rejectionReason}</p>
                                )}
                              </div>
                            ) : (
                              <span className="text-gray-300">—</span>
                            )}
                          </td>
                        )}
                        <td className="px-4 py-3">
                          <span
                            className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                            style={{ color: st.color, background: st.bg }}
                          >
                            <i className={st.icon}></i> {req.status}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          {req.status === 'HOD Approved' ? (
                            <div className="flex items-center justify-end gap-1">
                              <button
                                onClick={() => {
                                  setCommentModal(req.id);
                                  setForwardComment('');
                                }}
                                className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-white hover:opacity-90 cursor-pointer text-xs font-semibold whitespace-nowrap"
                                style={{ background: BRAND }}
                              >
                                <i className="ri-send-plane-line"></i> Approve → HR
                              </button>
                              <button
                                onClick={() => {
                                  setRejectModal(req.id);
                                  setRejectReason('');
                                }}
                                className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-amber-50 text-amber-600 hover:bg-amber-100 cursor-pointer text-xs font-semibold whitespace-nowrap"
                              >
                                <i className="ri-edit-line"></i> Request Review
                              </button>
                            </div>
                          ) : showActionButtons ? (
                            <div className="flex items-center justify-end gap-1">
                              <button
                                onClick={() => downloadLeaveComputationForm(req)}
                                title="Download Computation Form (PDF)"
                                className="flex items-center gap-1 px-2 py-1 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 cursor-pointer text-xs font-medium whitespace-nowrap"
                              >
                                <i className="ri-file-pdf-line"></i> Computation (PDF)
                              </button>
                              <span className="text-xs text-gray-400 italic ml-2">
                                {req.status === 'HOS Approved' ? 'Forwarded to HR' : req.status}
                              </span>
                            </div>
                          ) : (
                            <span className="text-xs text-gray-400 italic">Finalized</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
          <div className="px-5 py-2 border-t border-gray-50 bg-gray-50/30">
            <p className="text-xs text-gray-400">Showing {filtered.length} record(s)</p>
          </div>
        </div>
      </div>

      {/* Comment Modal */}
      {commentModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: '#fce7f3' }}>
                <i className="ri-send-plane-line text-lg" style={{ color: BRAND }}></i>
              </div>
              <div>
                <h3 className="font-bold text-gray-800">Approve & Forward to HR</h3>
                <p className="text-xs text-gray-500">Add a comment (optional) before forwarding</p>
              </div>
            </div>
            <div className="bg-gray-50 rounded-xl p-3 mb-4 text-xs text-gray-600">
              <p>
                <strong>Request:</strong> {requests.find((r) => r.id === commentModal)?.employee} —{' '}
                {requests.find((r) => r.id === commentModal)?.days} day(s)
              </p>
              <p className="mt-1"><strong>Timestamp:</strong> {new Date().toLocaleString()}</p>
            </div>
            <textarea
              value={forwardComment}
              onChange={(e) => setForwardComment(e.target.value)}
              rows={3}
              placeholder="Add forwarding comment for HR (optional)..."
              className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none mb-4"
            />
            <div className="flex gap-3">
              <button onClick={() => setCommentModal(null)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer">Cancel</button>
              <button onClick={handleApproveWithComment} className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer" style={{ background: BRAND }}>
                <i className="ri-send-plane-line mr-1"></i> Approve & Forward to HR
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Reject Modal */}
      {rejectModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <h3 className="font-bold text-gray-800 mb-1">Request Review</h3>
            <p className="text-sm text-gray-500 mb-4">Ask the HOD to review this request. The employee and HOD will be notified to resubmit.</p>
            <textarea value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} rows={3} placeholder="State reason for review request..." className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none mb-4" />
            <div className="flex gap-3">
              <button onClick={() => setRejectModal(null)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer">Cancel</button>
              <button onClick={handleReject} disabled={!rejectReason} className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold disabled:opacity-50 cursor-pointer" style={{ background: BRAND }}>
                Send Review Request
              </button>
            </div>
          </div>
        </div>
      )}
    </HOSLayout>
  );
}