import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  ArrowLeft, ArrowRight, UserMinus, ShieldAlert, Calendar, 
  HelpCircle, Landmark, CheckCircle2, AlertCircle, AlertTriangle 
} from 'lucide-react';
import api from '../../store/api';
import { useOffboardingStore } from '../../store/offboarding';
import { useAuthStore } from '../../store/auth';
import OffboardingStepRow from '../../components/OffboardingStepRow';
import OverrideModal from '../../components/OverrideModal';

interface PreflightData {
  role: 'student' | 'staff';
  user: {
    id: number;
    uid: string;
    first_name: string;
    last_name: string;
    email: string;
    id_number?: string;
    role?: string;
  };
  checks: {
    // Student
    enrollments?: any[];
    hostel?: { room_number: string; hostel_name: string } | null;
    transport?: number;
    clubs?: number;
    fees?: number;
    // Staff
    leave?: number;
    payroll?: { status: string; net_salary: number; period: string } | null;
    classes?: any[];
    subjects?: any[];
    roles?: any[];
  };
}

export default function OffboardingWizard() {
  const { userId } = useParams<{ userId: string }>();
  const navigate = useNavigate();
  const { offline } = useAuthStore();
  const { offboardStudent, offboardStaff } = useOffboardingStore();

  const [currentStep, setCurrentStep] = useState<number>(1);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [preflight, setPreflight] = useState<PreflightData | null>(null);

  // Form State
  const [reason, setReason] = useState<string>('');
  const [reasonNotes, setReasonNotes] = useState<string>('');
  const [effectiveDate, setEffectiveDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [destination, setDestination] = useState<string>('');
  const [overrideReason, setOverrideReason] = useState<string | null>(null);
  const [overrideModalStep, setOverrideModalStep] = useState<string | null>(null);

  useEffect(() => {
    if (!userId) return;
    setLoading(true);
    api.get(`/offboarding/preflight/${userId}`)
      .then((res) => {
        setPreflight(res.data);
        // Set default reason
        if (res.data.role === 'student') {
          setReason('withdrawn');
        } else {
          setReason('resigned');
        }
        setLoading(false);
      })
      .catch((err) => {
        setError(err.response?.data?.error || err.message || 'Failed to load preflight checklist');
        setLoading(false);
      });
  }, [userId]);

  if (loading) {
    return (
      <div className="py-20 text-center">
        <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
        <p className="text-text-muted font-bold uppercase tracking-widest text-xs">Loading preflight checklist...</p>
      </div>
    );
  }

  if (error || !preflight) {
    return (
      <div className="max-w-xl mx-auto py-16 px-6 text-center space-y-6">
        <div className="w-16 h-16 rounded-[1.5rem] bg-rose-50 dark:bg-rose-500/10 border border-rose-100 dark:border-rose-500/20 flex items-center justify-center text-rose-500 mx-auto">
          <AlertCircle size={28} />
        </div>
        <h2 className="text-2xl font-black text-text tracking-tight">Preflight Check Failed</h2>
        <p className="text-text-muted text-sm leading-relaxed">{error || 'Unable to retrieve staff/student records for offboarding.'}</p>
        <button
          onClick={() => navigate(-1)}
          className="inline-flex items-center gap-2 px-6 py-3 bg-muted hover:bg-muted/80 text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-all"
        >
          <ArrowLeft size={14} /> Back
        </button>
      </div>
    );
  }

  const { user, role, checks } = preflight;
  const isStudent = role === 'student';

  // Checklist Validation
  const hasOutstandingFees = isStudent && (checks.fees || 0) > 0;
  const hasUnpaidPayroll = !isStudent && checks.payroll && checks.payroll.status !== 'paid';

  const isFeeStepBlocked = hasOutstandingFees && !overrideReason;
  const isPayrollStepBlocked = hasUnpaidPayroll && !overrideReason;

  const isChecklistBlocked = isFeeStepBlocked || isPayrollStepBlocked;

  const handleApplyOverride = (reasonText: string) => {
    setOverrideReason(reasonText);
    setOverrideModalStep(null);
  };

  const handleCompleteOffboarding = async () => {
    if (offline || !navigator.onLine) {
      alert('Offline mode: You must be online to complete offboarding.');
      return;
    }

    setSubmitting(true);
    setError(null);

    const payload: any = {
      reason,
      reasonNotes,
      effectiveDate,
    };

    if (isStudent && reason === 'transferred') {
      payload.destination = destination;
    }

    if (overrideReason) {
      payload.override = {
        reason: overrideReason,
      };
    }

    try {
      if (isStudent) {
        await offboardStudent(user.id, payload);
      } else {
        await offboardStaff(user.id, payload);
      }
      navigate('/admin/offboarding');
    } catch (err: any) {
      setError(err.message || 'Offboarding failed. The transaction was rolled back.');
    } finally {
      setSubmitting(false);
    }
  };

  const nextStep = () => {
    if (currentStep === 1) {
      if (isStudent && reason === 'transferred' && !destination.trim()) {
        alert('Please specify the destination high school or transfer institution.');
        return;
      }
      setCurrentStep(2);
    } else if (currentStep === 2) {
      if (!effectiveDate) {
        alert('Please specify the effective date of offboarding.');
        return;
      }
      setCurrentStep(3);
    } else if (currentStep === 3) {
      if (isChecklistBlocked) {
        alert('Outstanding dues must be overridden or settled before proceeding.');
        return;
      }
      setCurrentStep(4);
    }
  };

  const prevStep = () => {
    setCurrentStep((s) => Math.max(1, s - 1));
  };

  return (
    <div className="max-w-2xl mx-auto space-y-8 animate-in fade-in duration-500 pb-16">
      {/* Breadcrumb / Top Bar */}
      <div className="flex items-center justify-between border-b border-border/60 pb-4">
        <button
          onClick={() => navigate(-1)}
          className="inline-flex items-center gap-2 text-text-muted hover:text-text text-sm font-bold transition-all"
        >
          <ArrowLeft size={16} /> Back
        </button>
        <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted bg-muted px-3 py-1.5 rounded-lg border border-border">
          Step {currentStep} of 4
        </span>
      </div>

      {/* Header */}
      <div>
        <h1 className="text-3xl font-black text-text tracking-tight flex items-center gap-3">
          <UserMinus className="text-primary shrink-0" size={28} />
          <span>Offboarding Wizard</span>
        </h1>
        <p className="text-sm text-text-muted mt-1">
          Initiating offboarding for {isStudent ? 'Student' : 'Staff Member'}:{' '}
          <strong className="text-text">{user.first_name} {user.last_name}</strong>
          {user.id_number && ` (${user.id_number})`}
        </p>
      </div>

      {error && (
        <div className="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-500 rounded-xl text-sm font-bold flex items-start gap-3">
          <AlertCircle className="shrink-0 mt-0.5" size={16} />
          <span>{error}</span>
        </div>
      )}

      {/* STEP 1: Reason and Notes */}
      {currentStep === 1 && (
        <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
          <h2 className="text-xl font-black text-text tracking-tight border-b border-border/60 pb-3 flex items-center gap-2">
            <span className="w-6 h-6 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xs font-black">1</span>
            Select Reason for Withdrawal
          </h2>

          <div className="space-y-4">
            <label className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
              Reason <span className="text-rose-500">*</span>
            </label>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {isStudent ? (
                <>
                  {['graduated', 'transferred', 'withdrawn', 'expelled', 'other'].map((r) => (
                    <label
                      key={r}
                      className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${
                        reason === r
                          ? 'border-primary bg-primary/5 text-primary'
                          : 'border-border bg-muted/20 hover:bg-muted/40 text-text'
                      }`}
                    >
                      <input
                        type="radio"
                        name="reason"
                        value={r}
                        checked={reason === r}
                        onChange={() => setReason(r)}
                        className="text-primary focus:ring-primary h-4 w-4 border-border"
                      />
                      <span className="text-xs font-black uppercase tracking-wider capitalize">{r}</span>
                    </label>
                  ))}
                </>
              ) : (
                <>
                  {['resigned', 'terminated', 'retired', 'deceased', 'other'].map((r) => (
                    <label
                      key={r}
                      className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${
                        reason === r
                          ? 'border-primary bg-primary/5 text-primary'
                          : 'border-border bg-muted/20 hover:bg-muted/40 text-text'
                      }`}
                    >
                      <input
                        type="radio"
                        name="reason"
                        value={r}
                        checked={reason === r}
                        onChange={() => setReason(r)}
                        className="text-primary focus:ring-primary h-4 w-4 border-border"
                      />
                      <span className="text-xs font-black uppercase tracking-wider capitalize">{r}</span>
                    </label>
                  ))}
                </>
              )}
            </div>
          </div>

          {isStudent && reason === 'transferred' && (
            <div className="space-y-2">
              <label htmlFor="destination" className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                Destination High School / Institution <span className="text-rose-500">*</span>
              </label>
              <input
                id="destination"
                type="text"
                placeholder="e.g. Hillside High School, Harare"
                value={destination}
                onChange={(e) => setDestination(e.target.value)}
                className="w-full px-4 py-3 rounded-xl border border-border bg-muted/30 text-text text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-primary/45"
              />
            </div>
          )}

          <div className="space-y-2">
            <label htmlFor="notes" className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
              Withdrawal Notes
            </label>
            <textarea
              id="notes"
              rows={4}
              placeholder="Provide extra details, explanation, or official memo remarks..."
              value={reasonNotes}
              onChange={(e) => setReasonNotes(e.target.value)}
              className="w-full px-4 py-3 rounded-xl border border-border bg-muted/30 text-text placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/45 text-sm font-semibold resize-none"
            />
          </div>

          <div className="flex justify-end pt-4">
            <button
              onClick={nextStep}
              className="px-6 py-3.5 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/95 transition-all shadow-md flex items-center gap-2"
            >
              <span>Continue</span>
              <ArrowRight size={14} />
            </button>
          </div>
        </div>
      )}

      {/* STEP 2: Effective Date */}
      {currentStep === 2 && (
        <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
          <h2 className="text-xl font-black text-text tracking-tight border-b border-border/60 pb-3 flex items-center gap-2">
            <span className="w-6 h-6 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xs font-black">2</span>
            Set Effective Date
          </h2>

          <div className="space-y-4">
            <p className="text-sm text-text-muted leading-relaxed">
              Choose the effective date on which the user is marked offboarded. Active positions, logins, and enrollments will terminate on this date.
            </p>

            <div className="relative max-w-sm">
              <Calendar size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
              <input
                type="date"
                value={effectiveDate}
                onChange={(e) => setEffectiveDate(e.target.value)}
                className="w-full pl-12 pr-4 py-3.5 rounded-xl border border-border bg-muted/30 text-text font-bold text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
              />
            </div>
          </div>

          <div className="flex justify-between pt-6 border-t border-border/60">
            <button
              onClick={prevStep}
              className="px-6 py-3.5 bg-muted hover:bg-muted/80 text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-all"
            >
              Back
            </button>
            <button
              onClick={nextStep}
              className="px-6 py-3.5 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/95 transition-all shadow-md flex items-center gap-2"
            >
              <span>Verify Checklist</span>
              <ArrowRight size={14} />
            </button>
          </div>
        </div>
      )}

      {/* STEP 3: Checklist */}
      {currentStep === 3 && (
        <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
          <h2 className="text-xl font-black text-text tracking-tight border-b border-border/60 pb-3 flex items-center gap-2">
            <span className="w-6 h-6 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xs font-black">3</span>
            Integrations & Clearance Checklist
          </h2>

          <div className="space-y-4">
            {isStudent ? (
              <>
                {/* 1. Enrollment */}
                <OffboardingStepRow
                  step="enrollment_closed"
                  label="Enrollment Gating"
                  status="completed"
                  notes={`Student holds ${checks.enrollments?.length || 0} active class enrollment(s). These will be marked '${reason === 'graduated' ? 'graduated' : reason === 'transferred' ? 'transferred' : 'inactive'}'.`}
                />

                {/* 2. Hostel Room */}
                <OffboardingStepRow
                  step="hostel_released"
                  label="Hostel Room Release"
                  status="completed"
                  notes={
                    checks.hostel
                      ? `Student is currently assigned to room ${checks.hostel.room_number} (${checks.hostel.hostel_name}). Room assignment will be closed and marked available.`
                      : 'No active hostel assignments.'
                  }
                />

                {/* 3. Transport routes */}
                <OffboardingStepRow
                  step="transport_removed"
                  label="Transport Allocations"
                  status="completed"
                  notes={
                    checks.transport && checks.transport > 0
                      ? `Student holds ${checks.transport} transport routes allocations. These will be deactivated.`
                      : 'No transport route allocations.'
                  }
                />

                {/* 4. Club memberships */}
                <OffboardingStepRow
                  step="clubs_removed"
                  label="Clubs & Extracurriculars"
                  status="completed"
                  notes={
                    checks.clubs && checks.clubs > 0
                      ? `Student is enrolled in ${checks.clubs} clubs. Club memberships will be deactivated and attendance logs soft-deleted.`
                      : 'No active club memberships.'
                  }
                />

                {/* 5. Fees Outstanding */}
                <OffboardingStepRow
                  step="fee_settled"
                  label="Finance & Tuition Fees"
                  status={isFeeStepBlocked ? 'blocked' : 'completed'}
                  notes={
                    hasOutstandingFees
                      ? overrideReason
                        ? `Finance Block Override: Outstanding fees ($${checks.fees}) bypassed with justification: "${overrideReason}"`
                        : `Student has an outstanding fees balance of $${checks.fees}. Bypassing requires administrator override.`
                      : 'No outstanding tuition fees.'
                  }
                  actionRequired={hasOutstandingFees && !overrideReason}
                  actionLabel="Override Block"
                  onActionClick={() => setOverrideModalStep('Tuition Fees')}
                />
              </>
            ) : (
              <>
                {/* 1. Leave requests */}
                <OffboardingStepRow
                  step="leave_closed"
                  label="Leave Requests"
                  status="completed"
                  notes={
                    checks.leave && checks.leave > 0
                      ? `Staff member has ${checks.leave} pending leave request(s). These will be auto-cancelled.`
                      : 'No pending leave requests.'
                  }
                />

                {/* 2. Payroll settle */}
                <OffboardingStepRow
                  step="payroll_finalized"
                  label="Payroll Finalization"
                  status={isPayrollStepBlocked ? 'blocked' : 'completed'}
                  notes={
                    hasUnpaidPayroll
                      ? overrideReason
                        ? `Payroll Block Override: Unpaid period (${checks.payroll?.period}, $${checks.payroll?.net_salary}) bypassed with justification: "${overrideReason}"`
                        : `Staff has unpaid payslip run for period ${checks.payroll?.period} ($${checks.payroll?.net_salary}). Bypassing requires administrator override.`
                      : 'No outstanding payroll runs.'
                  }
                  actionRequired={hasUnpaidPayroll && !overrideReason}
                  actionLabel="Override Block"
                  onActionClick={() => setOverrideModalStep('Payroll Runs')}
                />

                {/* 3. Class assignments */}
                <OffboardingStepRow
                  step="class_assignments_cleared"
                  label="Class Teacher Allocations"
                  status="completed"
                  notes={
                    checks.classes && checks.classes.length > 0
                      ? `Staff is class teacher for: ${checks.classes.map((c: any) => c.name).join(', ')}. These teacher associations will be cleared.`
                      : 'Not assigned as teacher for any classes.'
                  }
                />

                {/* 4. Subject assignments */}
                <OffboardingStepRow
                  step="subject_assignments_cleared"
                  label="Subject Teaching Classes"
                  status="completed"
                  notes={
                    checks.subjects && checks.subjects.length > 0
                      ? `Staff teaches: ${checks.subjects.map((s: any) => s.name).join(', ')}. Teacher allocations will be cleared. Also revoking ${checks.roles?.length || 0} active auxiliary role(s).`
                      : `No subject teaching classes. Also revoking ${checks.roles?.length || 0} active auxiliary role(s).`
                  }
                />
              </>
            )}

            {/* Standard account actions */}
            <OffboardingStepRow
              step="account_deactivated"
              label="Account & Login Gating"
              status="completed"
              notes="The user account's login ability is deactivated (is_active = 0)."
            />

            <OffboardingStepRow
              step="record_archived"
              label="Alumni / Former Staff Archive"
              status="completed"
              notes={`Archive status will be set to: ${isStudent ? (reason === 'expelled' ? 'inactive_alumni' : 'active_alumni') : 'former_staff'}`}
            />
          </div>

          <div className="flex justify-between pt-6 border-t border-border/60">
            <button
              onClick={prevStep}
              className="px-6 py-3.5 bg-muted hover:bg-muted/80 text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-all"
            >
              Back
            </button>
            <button
              onClick={nextStep}
              disabled={isChecklistBlocked}
              className="px-6 py-3.5 bg-primary disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/95 transition-all shadow-md flex items-center gap-2"
            >
              <span>Review Summary</span>
              <ArrowRight size={14} />
            </button>
          </div>
        </div>
      )}

      {/* STEP 4: Confirm */}
      {currentStep === 4 && (
        <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm space-y-6">
          <h2 className="text-xl font-black text-text tracking-tight border-b border-border/60 pb-3 flex items-center gap-2 text-rose-500">
            <AlertTriangle className="shrink-0" size={22} />
            Confirm Offboarding Action
          </h2>

          <div className="space-y-5">
            <p className="text-sm text-text-muted leading-relaxed">
              Please review the final summary of the offboarding case. This operation runs inside a database transaction and will execute all deactivations simultaneously.
            </p>

            {/* Summary details */}
            <div className="bg-muted/20 border border-border/60 rounded-2xl p-5 space-y-3 text-sm">
              <div className="flex justify-between">
                <span className="font-bold text-text-muted">Subject:</span>
                <span className="font-black text-text">{user.first_name} {user.last_name}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-bold text-text-muted">Type:</span>
                <span className="font-black text-text uppercase tracking-wider text-xs">{role}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-bold text-text-muted">Reason:</span>
                <span className="font-black text-primary uppercase tracking-wider text-xs">{reason}</span>
              </div>
              {destination && (
                <div className="flex justify-between">
                  <span className="font-bold text-text-muted">Transfer Destination:</span>
                  <span className="font-black text-text">{destination}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="font-bold text-text-muted">Effective Date:</span>
                <span className="font-black text-text">{effectiveDate}</span>
              </div>
              {overrideReason && (
                <div className="border-t border-border/40 pt-3 flex flex-col gap-1">
                  <span className="font-bold text-rose-500 flex items-center gap-1.5 text-xs">
                    <ShieldAlert size={14} /> Administrative Override Applied
                  </span>
                  <span className="text-xs text-text-muted italic">"{overrideReason}"</span>
                </div>
              )}
            </div>

            {offline || !navigator.onLine ? (
              <div className="p-4 bg-amber-500/10 border border-amber-500/20 text-amber-500 rounded-xl text-xs font-bold leading-relaxed flex items-start gap-3">
                <AlertTriangle className="shrink-0 mt-0.5" size={16} />
                <span>You are currently offline. You must be online to execute offboarding workflows. Please connect to the internet.</span>
              </div>
            ) : null}
          </div>

          <div className="flex justify-between pt-6 border-t border-border/60">
            <button
              onClick={prevStep}
              disabled={submitting}
              className="px-6 py-3.5 bg-muted hover:bg-muted/80 text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-all"
            >
              Back
            </button>
            <button
              onClick={handleCompleteOffboarding}
              disabled={submitting || offline || !navigator.onLine}
              className="px-8 py-3.5 bg-rose-600 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-rose-700 text-white rounded-xl font-black text-xs uppercase tracking-widest transition-all shadow-md flex items-center justify-center gap-2"
            >
              {submitting ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  <span>Processing...</span>
                </>
              ) : (
                <>
                  <UserMinus size={14} />
                  <span>Execute Offboard</span>
                </>
              )}
            </button>
          </div>
        </div>
      )}

      {/* Override Reason Capture Modal */}
      {overrideModalStep && (
        <OverrideModal
          isOpen={true}
          stepName={overrideModalStep}
          onConfirm={handleApplyOverride}
          onCancel={() => setOverrideModalStep(null)}
        />
      )}
    </div>
  );
}
