'use client';
import { useState } from 'react';
import { LeaveRequest, LEAVE_POLICIES } from './leaveData';
import { downloadApprovalLetterPdf } from '../../../lib/leaveComputationPdf';
import { downloadLeaveComputationForm, downloadLeaveComputationFormWord } from '../../../lib/leaveComputationForm';

interface Props {
  request: LeaveRequest;
  isHR?: boolean;
  isAdmin?: boolean;
  isEmployee?: boolean;
  onClose: () => void;
  onApprove?: (id: string) => void;
  onReject?: (id: string, reason: string) => void;
  onDelete?: (id: string) => void;
}

const STATUS_CONFIG: Record<string, { color: string; bg: string }> = {
  Pending: { color: '#d97706', bg: '#fef3c7' },
  'Pending Review': { color: '#7c3aed', bg: '#ede9fe' },
  'HOD Approved': { color: '#2563eb', bg: '#dbeafe' },
  'HOS Approved': { color: '#059669', bg: '#d1fae5' },
  Approved: { color: '#16a34a', bg: '#dcfce7' },
  Rejected: { color: '#dc2626', bg: '#fee2e2' },
  Cancelled: { color: '#6b7280', bg: '#f3f4f6' },
};

export default function LeaveDetailModal({ request, isHR = false, isAdmin = false, isEmployee = false, onClose, onApprove, onReject, onDelete }: Props) {
  const [showReject, setShowReject] = useState(false);
  const [rejectReason, setRejectReason] = useState('');

  const policy = LEAVE_POLICIES.find(p => p.type === request.type);
  const st = STATUS_CONFIG[request.status];

  const handleDownloadComputationPdf = () => {
    downloadLeaveComputationForm(request, 'CHRP ELIZABETH MUTUNGI');
  };

  const handleDownloadComputationWord = () => {
    downloadLeaveComputationFormWord(request, 'CHRP ELIZABETH MUTUNGI');
  };

  return (
    <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-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <div>
            <h3 className="font-bold text-gray-800 text-lg">{request.id}</h3>
            <p className="text-xs text-gray-400 mt-0.5">{policy?.label || request.type}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer">
            <i className="ri-close-line text-gray-500"></i>
          </button>
        </div>

        <div className="p-6 space-y-5">
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-gray-50 rounded-xl p-4">
              <p className="text-xs text-gray-400 mb-1">Employee</p>
              <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" style={{ background: '#b828a0' }}>
                  {request.employee.split(' ').map(n => n[0]).join('').slice(0, 2)}
                </div>
                <div>
                  <p className="font-semibold text-gray-800 text-sm">{request.employee}</p>
                  <p className="text-xs text-gray-400">{request.position}</p>
                </div>
              </div>
            </div>
            <div className="bg-gray-50 rounded-xl p-4">
              <p className="text-xs text-gray-400 mb-1">Department & Type</p>
              <p className="font-semibold text-gray-800">{request.dept}</p>
              <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${request.employeeType === 'Intern' ? 'bg-orange-100 text-orange-700' : 'bg-blue-100 text-blue-700'}`}>
                {request.employeeType}
              </span>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-3">
            <div className="bg-purple-50 rounded-xl p-3 text-center">
              <p className="text-xs text-gray-400">Start Date</p>
              <p className="font-bold text-gray-800 mt-1">{request.startDate}</p>
            </div>
            <div className="bg-purple-50 rounded-xl p-3 text-center">
              <p className="text-xs text-gray-400">End Date</p>
              <p className="font-bold text-gray-800 mt-1">{request.endDate}</p>
            </div>
            <div className="rounded-xl p-3 text-center" style={{ background: '#fdf4ff' }}>
              <p className="text-xs text-gray-400">Duration</p>
              <p className="font-bold text-2xl mt-0.5" style={{ color: '#b828a0' }}>{request.days}</p>
              <p className="text-xs text-gray-400">day(s)</p>
            </div>
          </div>

          {request.reason && (
            <div>
              <p className="text-xs font-semibold text-gray-500 mb-1.5 uppercase">Reason</p>
              <p className="text-sm text-gray-700 bg-gray-50 rounded-xl px-4 py-3">{request.reason}</p>
            </div>
          )}

          {request.rejectionReason && (
            <div className="bg-red-50 rounded-xl px-4 py-3">
              <p className="text-xs font-semibold text-red-500 mb-1 uppercase">Rejection Reason</p>
              <p className="text-sm text-red-700">{request.rejectionReason}</p>
            </div>
          )}

          {request.reviewComment && request.status === 'Pending Review' && (
            <div className="bg-violet-50 border border-violet-200 rounded-xl px-4 py-3">
              <p className="text-xs font-semibold text-violet-600 mb-1 uppercase">Review Requested</p>
              <p className="text-sm text-violet-800">{request.reviewComment}</p>
              {request.reviewBy && <p className="text-xs text-violet-500 mt-1">By: {request.reviewBy} on {request.reviewDate}</p>}
              {request.reviewNewStart && request.reviewNewEnd && (
                <p className="text-xs text-violet-500 mt-1">Suggested dates: {request.reviewNewStart} → {request.reviewNewEnd}</p>
              )}
            </div>
          )}

          {request.hosComment && (
            <div className="bg-emerald-50 border border-emerald-200 rounded-xl px-4 py-3">
              <div className="flex items-start gap-2">
                <i className="ri-chat-check-line text-emerald-600 mt-0.5 flex-shrink-0"></i>
                <div>
                  <p className="text-xs font-semibold text-emerald-700 uppercase mb-1">HOS / CEO Comment</p>
                  <p className="text-sm text-emerald-800">{request.hosComment}</p>
                  {request.hosApprovedBy && (
                    <p className="text-xs text-emerald-500 mt-1">
                      {request.hosApprovedBy} &mdash; {request.hosApprovedOn}
                    </p>
                  )}
                </div>
              </div>
            </div>
          )}

          {(request.hodApprovedBy || request.hosApprovedBy) && (
            <div className="bg-blue-50 rounded-xl px-4 py-3 space-y-2">
              <p className="text-xs font-semibold text-blue-600 uppercase">Approval Trail</p>
              {request.hodApprovedBy && (
                <div className="flex items-center gap-2 text-xs">
                  <i className="ri-shield-check-line text-blue-500"></i>
                  <span className="text-blue-700 font-medium">HOD:</span>
                  <span className="text-blue-600">{request.hodApprovedBy} on {request.hodApprovedOn}</span>
                </div>
              )}
              {request.hosApprovedBy && (
                <div className="flex items-center gap-2 text-xs">
                  <i className="ri-check-double-line text-emerald-600"></i>
                  <span className="text-emerald-700 font-medium">HOS:</span>
                  <span className="text-emerald-600">{request.hosApprovedBy} on {request.hosApprovedOn}</span>
                </div>
              )}
            </div>
          )}

          {request.approvedBy && (
            <div className="bg-green-50 rounded-xl px-4 py-3 flex items-center gap-3">
              <i className="ri-checkbox-circle-line text-green-600 text-lg"></i>
              <div>
                <p className="text-sm font-semibold text-green-700">Approved by {request.approvedBy}</p>
                {request.approvedOn && <p className="text-xs text-green-500">on {request.approvedOn}</p>}
              </div>
            </div>
          )}

          <div className="bg-gray-50 rounded-xl px-4 py-3 text-xs text-gray-500">
            <p><strong>Submitted:</strong> {request.submittedOn}</p>
            <p className="mt-1 text-amber-600"><i className="ri-lock-line mr-1"></i>Leave records are locked and cannot be edited after submission.</p>
          </div>

          {showReject && (
            <div className="bg-red-50 rounded-xl p-4">
              <p className="text-sm font-semibold text-red-700 mb-2">Rejection Reason *</p>
              <textarea value={rejectReason} onChange={e => setRejectReason(e.target.value)} rows={3}
                placeholder="State reason for rejection..."
                className="w-full border border-red-200 rounded-lg px-3 py-2 text-sm outline-none resize-none bg-white" />
              <div className="flex gap-2 mt-3">
                <button onClick={() => { if (rejectReason && onReject) onReject(request.id, rejectReason); }}
                  disabled={!rejectReason}
                  className="flex-1 py-2 rounded-lg bg-red-600 text-white text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap">
                  Confirm Rejection
                </button>
                <button onClick={() => setShowReject(false)}
                  className="px-4 py-2 rounded-lg border border-gray-200 text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              </div>
            </div>
          )}
        </div>

        <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end flex-wrap">
          {request.status === 'Approved' && !isHR && (
            <button onClick={() => downloadApprovalLetterPdf(request)}
              className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-semibold text-white cursor-pointer whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              <i className="ri-download-line"></i> Approval Letter
            </button>
          )}
          {isAdmin && onDelete && (
            <button onClick={() => onDelete(request.id)}
              className="px-4 py-2 border border-red-100 text-red-500 rounded-lg text-sm cursor-pointer hover:bg-red-50 whitespace-nowrap">
              <i className="ri-delete-bin-line mr-1"></i>Delete
            </button>
          )}
          <button onClick={onClose}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm cursor-pointer whitespace-nowrap">Close</button>
        </div>
      </div>
    </div>
  );
}