import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Calendar, UserMinus, UserCheck, X, FileText, CheckCircle2, AlertCircle, RefreshCw, Plus } from 'lucide-react';
import { useOffboardingStore, OffboardingRecord } from '../../store/offboarding';
import { useAuthStore } from '../../store/auth';
import { Modal } from '../../components/ui/Modal';
import ConfirmationModal from '../../components/ConfirmationModal';
import InitiateOffboardingModal from '../../components/InitiateOffboardingModal';

export default function Offboarding() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { records, loading, error, fetchRecords, cancelOffboarding } = useOffboardingStore();

  const [activeTab, setActiveTab] = useState<'student' | 'staff'>('student');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [selectedRecord, setSelectedRecord] = useState<OffboardingRecord | null>(null);
  const [recordDetails, setRecordDetails] = useState<OffboardingRecord | null>(null);
  const [actionLoading, setActionLoading] = useState<boolean>(false);
  const [cancelTargetId, setCancelTargetId] = useState<number | null>(null);
  const [showInitiateModal, setShowInitiateModal] = useState<boolean>(false);

  useEffect(() => {
    fetchRecords({
      audience: activeTab,
      status: statusFilter === 'all' ? undefined : statusFilter,
    });
  }, [activeTab, statusFilter, fetchRecords]);

  // Load full details (including actions) when a record is selected.
  // Guard against the race where the user clicks record A then B before
  // A's fetch resolves — only apply the response if it's still the
  // latest selection. Clearing recordDetails on selection change also
  // prevents the previous record's data from flashing while the new
  // fetch is in flight.
  useEffect(() => {
    if (!selectedRecord) {
      setRecordDetails(null);
      return;
    }
    let cancelled = false;
    setRecordDetails(null);
    useOffboardingStore
      .getState()
      .fetchRecordDetails(selectedRecord.id)
      .then((details) => {
        if (cancelled || !details) return;
        setRecordDetails(details);
      })
      .catch(() => {
        if (!cancelled) setRecordDetails(null);
      });
    return () => {
      cancelled = true;
    };
  }, [selectedRecord]);

  const handleCancelOffboarding = async (id: number) => {
    setActionLoading(true);
    try {
      await cancelOffboarding(id);
      setSelectedRecord(null);
      setCancelTargetId(null);
      fetchRecords({
        audience: activeTab,
        status: statusFilter === 'all' ? undefined : statusFilter,
      });
    } catch (err: any) {
      alert(err.response?.data?.error || err.message || 'Cancellation failed');
    } finally {
      setActionLoading(false);
    }
  };

  const filteredRecords = records.filter((r) => {
    const name = r.user_name || '';
    const idNum = r.user_id_number || '';
    const term = searchQuery.toLowerCase();
    return name.toLowerCase().includes(term) || idNum.toLowerCase().includes(term);
  });

  const getReasonColor = (reason: string) => {
    switch (reason) {
      case 'graduated':
        return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/20 dark:text-emerald-400 dark:border-emerald-800/30';
      case 'expelled':
      case 'terminated':
        return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/20 dark:text-rose-400 dark:border-rose-800/30';
      case 'transferred':
      case 'resigned':
        return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/20 dark:text-blue-400 dark:border-blue-800/30';
      default:
        return 'bg-slate-50 text-slate-700 border-slate-200 dark:bg-slate-900/20 dark:text-slate-400 dark:border-slate-800/30';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-500/10 dark:text-emerald-400';
      case 'cancelled':
        return 'bg-rose-100 text-rose-800 dark:bg-rose-500/10 dark:text-rose-400';
      default:
        return 'bg-amber-100 text-amber-800 dark:bg-amber-500/10 dark:text-amber-400';
    }
  };

  const canManage = ['school_admin', 'systems_admin', 'principal'].includes(user?.role || '');

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      {/* Page Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight">Offboarding Directory</h1>
          <p className="text-sm text-text-muted mt-1">
            Audit logs and records of students and staff members who have left the institution.
          </p>
        </div>
        {canManage && (
          <button
            onClick={() => setShowInitiateModal(true)}
            className="px-5 py-3 bg-primary hover:bg-primary/95 text-white rounded-xl font-black text-xs uppercase tracking-widest transition-all shadow-md flex items-center justify-center gap-2 active:scale-95 shrink-0"
          >
            <UserMinus size={16} />
            <span>Offboard Student / Staff</span>
          </button>
        )}
      </div>

      {/* Tabs */}
      <div className="flex gap-2 border-b border-border pb-px">
        <button
          onClick={() => { setActiveTab('student'); setSelectedRecord(null); }}
          className={`pb-3 px-4 font-bold text-sm border-b-2 transition-all ${
            activeTab === 'student'
              ? 'border-primary text-primary font-black'
              : 'border-transparent text-text-muted hover:text-text'
          }`}
        >
          Students
        </button>
        <button
          onClick={() => { setActiveTab('staff'); setSelectedRecord(null); }}
          className={`pb-3 px-4 font-bold text-sm border-b-2 transition-all ${
            activeTab === 'staff'
              ? 'border-primary text-primary font-black'
              : 'border-transparent text-text-muted hover:text-text'
          }`}
        >
          Staff Directory
        </button>
      </div>

      {/* Filter and Search Bar */}
      <div className="bg-card border border-border rounded-2xl p-4 flex flex-col md:flex-row gap-3">
        <div className="flex-1 relative">
          <Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
          <input
            type="text"
            placeholder="Search by name or reference number..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-border bg-background/50 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
          />
        </div>

        <select
          aria-label="Filter by status"
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-4 py-2.5 rounded-xl border border-border bg-background text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
        >
          <option value="all">All Statuses</option>
          <option value="completed">Completed</option>
          <option value="cancelled">Cancelled</option>
          <option value="in_progress">In Progress</option>
        </select>
      </div>

      {/* Error display */}
      {error && (
        <div className="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-500 rounded-xl text-sm font-bold">
          {error}
        </div>
      )}

      {/* Listing Content */}
      <div className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
        {loading && records.length === 0 ? (
          <div className="py-20 text-center">
            <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-text-muted text-sm font-bold uppercase tracking-wider">Loading offboarding cases...</p>
          </div>
        ) : filteredRecords.length === 0 ? (
          <div className="py-20 text-center">
            <UserMinus className="w-12 h-12 text-text-muted/40 mx-auto mb-4" />
            <p className="text-text-muted text-sm font-extrabold">No offboarding records match the filters</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-border bg-muted/40 text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                  <th className="px-6 py-4">Subject</th>
                  <th className="px-6 py-4">Reason</th>
                  <th className="px-6 py-4">Effective Date</th>
                  <th className="px-6 py-4">Initiated By</th>
                  <th className="px-6 py-4">Status</th>
                  <th className="px-6 py-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border/60">
                {filteredRecords.map((record) => (
                  <tr
                    key={record.id}
                    className="hover:bg-muted/20 transition-colors group cursor-pointer"
                    onClick={() => setSelectedRecord(record)}
                  >
                    <td className="px-6 py-5">
                      <div className="font-extrabold text-text group-hover:text-primary transition-colors">
                        {record.user_name}
                      </div>
                      <div className="text-[0.65rem] font-bold text-text-muted uppercase tracking-wider mt-0.5">
                        {record.user_id_number || 'No reference'}
                      </div>
                    </td>
                    <td className="px-6 py-5">
                      <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-wider border ${getReasonColor(record.reason)}`}>
                        {record.reason}
                      </span>
                    </td>
                    <td className="px-6 py-5 font-bold text-xs text-text-muted">
                      {new Date(record.effective_date).toLocaleDateString(undefined, {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric',
                      })}
                    </td>
                    <td className="px-6 py-5">
                      <div className="font-bold text-xs text-text">{record.initiator_name || 'System'}</div>
                      <div className="text-[0.6rem] font-bold text-text-muted uppercase tracking-wider mt-0.5">
                        {new Date(record.created_at).toLocaleDateString()}
                      </div>
                    </td>
                    <td className="px-6 py-5">
                      <span className={`px-2.5 py-0.5 rounded-full text-[0.6rem] font-black uppercase tracking-wider ${getStatusColor(record.status)}`}>
                        {record.status}
                      </span>
                    </td>
                    <td className="px-6 py-5 text-right" onClick={(e) => e.stopPropagation()}>
                      <button
                        onClick={() => setSelectedRecord(record)}
                        className="p-2 bg-muted hover:bg-primary hover:text-white rounded-xl text-text-muted transition-all"
                        aria-label={`View details for ${record.user_name || 'record'}`}
                      >
                        <FileText size={14} aria-hidden="true" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Record details modal */}
      {selectedRecord && (
        <Modal
          open={true}
          onClose={() => setSelectedRecord(null)}
          title="Offboarding Details"
          subtitle={`Workflow Case • ${selectedRecord.user_name}`}
          icon={UserMinus}
          watermarkIcon={UserMinus}
          maxWidth="max-w-2xl"
          zIndex={150}
        >
          <div className="space-y-6">
            {/* Case Header Status & Info */}
            <div className="flex justify-between items-center bg-muted/40 border border-border p-4 rounded-2xl">
              <div>
                <p className="text-[0.6rem] uppercase font-black tracking-[2px] text-primary">Subject Name</p>
                <h3 className="text-lg font-black text-text leading-tight mt-0.5">{selectedRecord.user_name}</h3>
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-black uppercase tracking-wider ${getStatusColor(selectedRecord.status)}`}>
                {selectedRecord.status}
              </span>
            </div>

            {/* Summary Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 bg-muted/20 border border-border/50 rounded-2xl p-4">
              <div>
                <span className="text-[0.6rem] font-black uppercase text-text-muted block">Withdrawal Reason</span>
                <span className="text-sm font-bold text-text capitalize mt-0.5 block">{selectedRecord.reason}</span>
              </div>
              <div>
                <span className="text-[0.6rem] font-black uppercase text-text-muted block">Effective Date</span>
                <span className="text-sm font-bold text-text mt-0.5 block">{selectedRecord.effective_date}</span>
              </div>
              {selectedRecord.destination && (
                <div className="col-span-1 sm:col-span-2 border-t border-border/40 pt-3">
                  <span className="text-[0.6rem] font-black uppercase text-text-muted block">Destination / School</span>
                  <span className="text-sm font-bold text-text mt-0.5 block">{selectedRecord.destination}</span>
                </div>
              )}
              {selectedRecord.reason_notes && (
                <div className="col-span-1 sm:col-span-2 border-t border-border/40 pt-3">
                  <span className="text-[0.6rem] font-black uppercase text-text-muted block">Withdrawal Notes</span>
                  <p className="text-xs text-text-muted mt-1 leading-relaxed">{selectedRecord.reason_notes}</p>
                </div>
              )}
            </div>

            {/* Checklist Workflow */}
            <div className="space-y-4">
              <h4 className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted border-b border-border/60 pb-2">
                Workflow Actions & Steps
              </h4>
              
              {!recordDetails ? (
                <div className="py-10 text-center">
                  <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                  <p className="text-text-muted text-xs font-bold uppercase tracking-wider">Loading steps...</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {recordDetails.actions?.map((action) => (
                    <div
                      key={action.id}
                      className="p-4 rounded-2xl border border-border bg-background/40 flex items-start justify-between gap-3"
                    >
                      <div className="min-w-0">
                        <span className="text-xs font-extrabold text-text capitalize">
                          {action.step.replace(/_/g, ' ')}
                        </span>
                        {action.notes && (
                          <p className="text-[0.7rem] text-text-muted mt-1 break-words">{action.notes}</p>
                        )}
                        <span className="text-[0.55rem] text-text-muted/65 block mt-2">
                          Performed by {action.performed_by_name || 'System'} at {new Date(action.performed_at).toLocaleString()}
                        </span>
                      </div>
                      <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-wider shrink-0 border ${
                        action.status === 'completed'
                          ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400'
                          : action.status === 'skipped'
                          ? 'bg-slate-100 text-slate-600 border-slate-200 dark:bg-slate-800 dark:text-slate-400'
                          : 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400'
                      }`}>
                        {action.status}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Cancel Button — opens the confirmation modal. The actual
                API call happens in handleCancelOffboarding via the
                ConfirmationModal; that modal owns the loading spinner. */}
            {canManage && selectedRecord.status !== 'cancelled' && (
              <div className="border-t border-border pt-6">
                <button
                  type="button"
                  onClick={() => setCancelTargetId(selectedRecord.id)}
                  className="w-full py-3.5 bg-rose-500/10 text-rose-500 hover:bg-rose-500/20 border border-rose-500/20 rounded-xl font-black uppercase text-xs tracking-widest transition-all flex items-center justify-center gap-2"
                >
                  <UserCheck size={14} />
                  <span>Re-activate User / Cancel Offboard</span>
                </button>
              </div>
            )}
          </div>
        </Modal>
      )}

      {/* Initiation Modal for selecting student/staff from school database */}
      <InitiateOffboardingModal
        isOpen={showInitiateModal}
        onClose={() => setShowInitiateModal(false)}
        onSuccess={() => {
          fetchRecords({
            audience: activeTab,
            status: statusFilter === 'all' ? undefined : statusFilter,
          });
        }}
      />

      {/* Confirmation Modal for Cancellation / Reactivation */}
      <ConfirmationModal
        isOpen={cancelTargetId !== null}
        title="Re-activate User & Cancel Offboarding"
        message="Are you sure you want to cancel this offboarding process? This action will immediately re-activate the user account and restore their active status in the institution directory."
        confirmText="Re-activate Account"
        cancelText="Keep Offboarded"
        variant="danger"
        isLoading={actionLoading}
        onConfirm={() => cancelTargetId && handleCancelOffboarding(cancelTargetId)}
        onCancel={() => setCancelTargetId(null)}
      />
    </div>
  );
}
