'use client';
import { EmployeeTerminationRequest } from '../../hr/termination/terminationData';

interface Props {
  request: EmployeeTerminationRequest;
  onBack: () => void;
  onWithdraw: (id: string) => void;
}

const STEPS = [
  { key: 'Pending HOD Review', label: 'HOD Review', icon: 'ri-user-star-line' },
  { key: 'Pending Manager Review', label: 'Manager Review', icon: 'ri-user-settings-line' },
  { key: 'Pending HR Review', label: 'HR Review', icon: 'ri-shield-user-line' },
  { key: 'Approved', label: 'Approved', icon: 'ri-checkbox-circle-fill' },
];

const statusColors: Record<string, string> = {
  'Pending HOD Review': '#7c3aed',
  'Pending Manager Review': '#f59e0b',
  'Pending HR Review': '#3b82f6',
  'Approved': '#10b981',
  'Rejected': '#ef4444',
  'Withdrawn': '#6b7280',
};

const statusIcons: Record<string, string> = {
  'Pending HOD Review': 'ri-user-star-line',
  'Pending Manager Review': 'ri-time-line',
  'Pending HR Review': 'ri-user-settings-line',
  'Approved': 'ri-checkbox-circle-fill',
  'Rejected': 'ri-close-circle-fill',
  'Withdrawn': 'ri-arrow-go-back-line',
};

export default function EmployeeTerminationStatus({ request, onBack, onWithdraw }: Props) {
  const isPending = ['Pending HOD Review', 'Pending Manager Review', 'Pending HR Review'].includes(request.status);
  const color = statusColors[request.status] || '#b828a0';
  const icon = statusIcons[request.status] || 'ri-information-line';
  const currentStepIdx = STEPS.findIndex(s => s.key === request.status);
  const isApproved = request.status === 'Approved';
  const isRejected = request.status === 'Rejected';

  const handleDownloadLetter = () => {
    const content = `UWEZO FUND
TERMINATION APPROVAL LETTER

Date: ${request.hrApprovedDate || new Date().toISOString().split('T')[0]}
Reference: ${request.applicationId}

To: ${request.employeeName}
Department: ${request.department}

Dear ${request.employeeName.split(' ')[0]},

RE: APPROVAL OF TERMINATION REQUEST

This letter confirms that your voluntary termination request has been reviewed and APPROVED by the relevant authorities.

TERMINATION DETAILS:
- Employee Name: ${request.employeeName}
- Department: ${request.department}
- Reason: ${request.reason}${request.reasonOther ? ` — ${request.reasonOther}` : ''}
- Proposed Last Day: ${request.proposedLastDay}
- Final Termination Date: ${request.finalTerminationDate || request.proposedLastDay}

APPROVAL TRAIL:
- HOD Approved: ${request.managerApprovedDate || 'N/A'}
- Manager Approved: ${request.managerApprovedDate || 'N/A'}
- HR Approved: ${request.hrApprovedDate || 'N/A'}

Please ensure you complete all handover procedures before your last working day.

_______________________________
HR MANAGER
UWEZO FUND

Uwezo Fund HRMS Version 2.0.1 © 2026`.trim();

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `Termination-Approval-${request.applicationId}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="max-w-2xl mx-auto space-y-5">
      <button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 cursor-pointer">
        <div className="w-4 h-4 flex items-center justify-center"><i className="ri-arrow-left-line"></i></div>
        Back to My Requests
      </button>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <div className="flex items-center gap-4 mb-5">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0" style={{ background: color + '18' }}>
            <i className={`${icon} text-2xl`} style={{ color }}></i>
          </div>
          <div className="flex-1">
            <p className="text-xs text-gray-500 font-mono">{request.applicationId}</p>
            <h2 className="text-xl font-bold text-gray-800">{request.status}</h2>
          </div>
          {isApproved && (
            <button onClick={handleDownloadLetter}
              className="flex items-center gap-2 px-4 py-2 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              <i className="ri-download-line"></i> Download Letter
            </button>
          )}
        </div>

        <div className="grid grid-cols-2 gap-3 text-sm">
          {[
            { label: 'Submission Date', value: request.submittedDate },
            { label: 'Proposed Last Day', value: request.proposedLastDay },
            { label: 'Reason', value: request.reason + (request.reasonOther ? ` — ${request.reasonOther}` : '') },
            { label: 'Department', value: request.department },
          ].map(item => (
            <div key={item.label} className="bg-gray-50 rounded-xl p-3">
              <p className="text-xs font-semibold text-gray-500 mb-1">{item.label.toUpperCase()}</p>
              <p className="text-sm font-medium text-gray-800">{item.value}</p>
            </div>
          ))}
        </div>

        {request.documentName && (
          <div className="mt-4 flex items-center gap-3 p-3 bg-blue-50 border border-blue-200 rounded-xl">
            <div className="w-8 h-8 flex items-center justify-center rounded-lg bg-blue-100">
              <i className="ri-file-text-line text-blue-600"></i>
            </div>
            <span className="text-sm text-blue-700 flex-1">{request.documentName}</span>
            <button className="text-xs text-blue-600 font-medium underline cursor-pointer whitespace-nowrap">Download</button>
          </div>
        )}

        {isPending && (
          <div className="mt-5 pt-5 border-t border-gray-100">
            <button onClick={() => onWithdraw(request.id)}
              className="flex items-center gap-2 px-4 py-2 rounded-xl border border-red-200 text-red-600 text-sm font-medium cursor-pointer whitespace-nowrap hover:bg-red-50">
              <div className="w-4 h-4 flex items-center justify-center"><i className="ri-arrow-go-back-line"></i></div>
              Withdraw Application
            </button>
            <p className="text-xs text-gray-400 mt-2">You can withdraw your application while it is still pending review.</p>
          </div>
        )}
      </div>

      {request.status !== 'Withdrawn' && (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-semibold text-gray-800 mb-5">Approval Progress</h3>
          <div className="flex items-start gap-0 mb-6">
            {STEPS.map((step, i) => {
              const done = isApproved || (currentStepIdx > i && currentStepIdx !== -1);
              const active = !isApproved && !isRejected && currentStepIdx === i;
              return (
                <div key={step.key} className="flex items-center flex-1">
                  <div className="flex flex-col items-center flex-1">
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all ${done ? 'border-transparent' : active ? 'border-current' : 'border-gray-200'}`}
                      style={done ? { background: '#10b981' } : active ? { borderColor: '#b828a0', background: '#fdf0fc' } : {}}>
                      {done ? (
                        <i className="ri-check-line text-white text-sm"></i>
                      ) : active ? (
                        <div className="w-3 h-3 rounded-full" style={{ background: '#b828a0' }}></div>
                      ) : (
                        <div className="w-3 h-3 rounded-full bg-gray-200"></div>
                      )}
                    </div>
                    <p className={`text-xs mt-2 text-center font-medium leading-tight px-1 ${done ? 'text-green-700' : active ? 'text-gray-800' : 'text-gray-400'}`}
                      style={active ? { color: '#b828a0' } : {}}>
                      {step.label}
                    </p>
                  </div>
                  {i < STEPS.length - 1 && (
                    <div className="h-0.5 w-6 flex-shrink-0 mx-0.5 mt-[-20px]" style={{ background: done ? '#10b981' : '#e5e7eb' }}></div>
                  )}
                </div>
              );
            })}
          </div>

          {isRejected && (
            <div className="p-4 bg-red-50 border border-red-200 rounded-xl">
              <p className="text-sm font-semibold text-red-700 mb-1">Application Rejected</p>
              <p className="text-sm text-red-600">{request.hrComments || request.managerComments || 'Your application was not approved.'}</p>
            </div>
          )}
          {isApproved && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-xl">
              <p className="text-sm font-semibold text-green-700 mb-1">Application Approved</p>
              <p className="text-sm text-green-600">Your termination has been approved. Final date: {request.finalTerminationDate || request.proposedLastDay}. Download your approval letter above.</p>
            </div>
          )}
        </div>
      )}

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <h3 className="font-semibold text-gray-800 mb-4">Activity Timeline</h3>
        <div className="space-y-4">
          {request.timeline.map((t, i) => (
            <div key={i} className="flex gap-3">
              <div className="flex flex-col items-center">
                <div className="w-3 h-3 rounded-full mt-1 flex-shrink-0" style={{ background: '#b828a0' }}></div>
                {i < request.timeline.length - 1 && <div className="w-0.5 flex-1 mt-1" style={{ background: '#e9d5f7' }}></div>}
              </div>
              <div className="pb-4">
                <p className="text-sm font-semibold text-gray-800">{t.step}</p>
                <p className="text-xs text-gray-500">{t.date} · {t.actor}</p>
                {t.note && <p className="text-xs text-gray-600 mt-0.5 italic bg-gray-50 rounded-lg px-3 py-1.5 mt-1">"{t.note}"</p>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
