import React, { useState, useEffect, useRef } from 'react';
import { Search, UserMinus, User, GraduationCap, Briefcase, Check, X, ChevronDown, Calendar, AlertCircle, Building2 } from 'lucide-react';
import { Modal } from './ui/Modal';
import { useOffboardingStore } from '../store/offboarding';
import api from '../store/api';

interface SchoolUser {
  id: number;
  uid: string;
  id_number?: string;
  first_name: string;
  last_name: string;
  email: string;
  role: string;
  status?: string;
  is_active?: number | boolean;
}

interface InitiateOffboardingModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export const InitiateOffboardingModal: React.FC<InitiateOffboardingModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const { offboardStudent, offboardStaff } = useOffboardingStore();

  // User Search State
  const [usersList, setUsersList] = useState<SchoolUser[]>([]);
  const [loadingUsers, setLoadingUsers] = useState<boolean>(false);
  const [userSearchQuery, setUserSearchQuery] = useState<string>('');
  const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
  const [selectedUser, setSelectedUser] = useState<SchoolUser | null>(null);
  const searchContainerRef = useRef<HTMLDivElement | null>(null);

  // Form Fields
  const [audience, setAudience] = useState<'student' | 'staff'>('student');
  const [reason, setReason] = useState<string>('withdrawn');
  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>('');

  const [submitting, setSubmitting] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  // Load active users
  useEffect(() => {
    if (!isOpen) return;
    setLoadingUsers(true);
    api.get('/users', { params: { limit: 1000 } })
      .then((res) => {
        const raw = res.data.users || res.data || [];
        const rawArray = Array.isArray(raw) ? raw : [];
        const activeOnly = rawArray.filter((u: SchoolUser) => {
          if (u.is_active !== undefined) return Boolean(u.is_active);
          if (u.status !== undefined) return u.status === 'active';
          return true;
        });
        setUsersList(activeOnly);
      })
      .catch((err) => {
        console.error('Failed to load users for offboarding modal:', err);
      })
      .finally(() => setLoadingUsers(false));
  }, [isOpen]);

  // Sync reason defaults when audience changes
  useEffect(() => {
    if (audience === 'student') {
      setReason('withdrawn');
    } else {
      setReason('resigned');
    }
  }, [audience]);

  // Close search dropdown on outside click
  useEffect(() => {
    if (!isDropdownOpen) return;
    const onDocMouseDown = (e: MouseEvent) => {
      const root = searchContainerRef.current;
      if (root && e.target instanceof Node && !root.contains(e.target)) {
        setIsDropdownOpen(false);
      }
    };
    const onDocKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setIsDropdownOpen(false);
    };
    document.addEventListener('mousedown', onDocMouseDown);
    document.addEventListener('keydown', onDocKeyDown);
    return () => {
      document.removeEventListener('mousedown', onDocMouseDown);
      document.removeEventListener('keydown', onDocKeyDown);
    };
  }, [isDropdownOpen]);

  // Filter users based on search query & selected audience filter
  const filteredUsers = usersList.filter((u) => {
    const isStudent = (u.role || '').toLowerCase() === 'student';
    const isTargetAudience = audience === 'student' ? isStudent : !isStudent;
    if (!isTargetAudience) return false;

    if (!userSearchQuery.trim()) return true;
    const query = userSearchQuery.toLowerCase().trim();
    const firstName = (u.first_name || '').toLowerCase();
    const lastName = (u.last_name || '').toLowerCase();
    const fullName = `${firstName} ${lastName}`.trim();
    const email = (u.email || '').toLowerCase();
    const idNum = (u.id_number || '').toLowerCase();
    return fullName.includes(query) || firstName.includes(query) || lastName.includes(query) || email.includes(query) || idNum.includes(query);
  });

  const handleSelectUser = (user: SchoolUser) => {
    setSelectedUser(user);
    setIsDropdownOpen(false);
    setUserSearchQuery('');
    if ((user.role || '').toLowerCase() === 'student') {
      setAudience('student');
    } else {
      setAudience('staff');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedUser) {
      setError('Please select a student or staff member');
      return;
    }

    if (audience === 'student' && reason === 'transferred' && !destination.trim()) {
      setError('Please specify the destination high school / institution');
      return;
    }

    setSubmitting(true);
    setError(null);

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

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

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

    try {
      if (audience === 'student') {
        await offboardStudent(selectedUser.id, payload);
      } else {
        await offboardStaff(selectedUser.id, payload);
      }
      onSuccess();
      onClose();
      resetForm();
    } catch (err: any) {
      setError(err.message || 'Failed to initiate offboarding. Please verify requirements.');
    } finally {
      setSubmitting(false);
    }
  };

  const resetForm = () => {
    setSelectedUser(null);
    setUserSearchQuery('');
    setReasonNotes('');
    setDestination('');
    setOverrideReason('');
    setError(null);
  };

  if (!isOpen) return null;

  return (
    <Modal
      open={isOpen}
      onClose={onClose}
      title="Initiate User Offboarding"
      subtitle="Select a student or staff member to begin the offboarding workflow"
      icon={UserMinus}
      watermarkIcon={UserMinus}
      maxWidth="max-w-2xl"
      zIndex={160}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        {error && (
          <div className="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-500 rounded-2xl text-xs font-bold flex items-start gap-3">
            <AlertCircle className="shrink-0 mt-0.5" size={16} />
            <span>{error}</span>
          </div>
        )}

        {/* 1. Audience Selector */}
        <div className="space-y-2">
          <label className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
            Target User Type <span className="text-rose-500">*</span>
          </label>
          <div className="grid grid-cols-2 gap-3">
            <button
              type="button"
              onClick={() => {
                setAudience('student');
                if (selectedUser && selectedUser.role !== 'student') setSelectedUser(null);
              }}
              className={`flex items-center justify-center gap-2 p-3.5 rounded-2xl border font-bold text-xs uppercase tracking-wider transition-all ${
                audience === 'student'
                  ? 'border-primary bg-primary/10 text-primary shadow-sm'
                  : 'border-border bg-muted/20 text-text-muted hover:text-text'
              }`}
            >
              <GraduationCap size={18} />
              <span>Student</span>
            </button>

            <button
              type="button"
              onClick={() => {
                setAudience('staff');
                if (selectedUser && selectedUser.role === 'student') setSelectedUser(null);
              }}
              className={`flex items-center justify-center gap-2 p-3.5 rounded-2xl border font-bold text-xs uppercase tracking-wider transition-all ${
                audience === 'staff'
                  ? 'border-primary bg-primary/10 text-primary shadow-sm'
                  : 'border-border bg-muted/20 text-text-muted hover:text-text'
              }`}
            >
              <Briefcase size={18} />
              <span>Staff Member</span>
            </button>
          </div>
        </div>

        {/* 2. User Searchbar & Dropdown */}
        <div className="space-y-2 relative">
          <label className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
            Select {audience === 'student' ? 'Student' : 'Staff Member'} <span className="text-rose-500">*</span>
          </label>

          {selectedUser ? (
            /* Selected User Card */
            <div className="flex items-center justify-between p-4 rounded-2xl border border-primary/30 bg-primary/5 dark:bg-primary/10">
              <div className="flex items-center gap-3.5">
                <div className="w-10 h-10 rounded-xl bg-primary text-white font-black flex items-center justify-center text-sm shadow-md">
                  {(selectedUser.first_name || 'U')[0]}{(selectedUser.last_name || '')[0] || ''}
                </div>
                <div>
                  <h4 className="font-extrabold text-sm text-text flex items-center gap-2">
                    <span>{selectedUser.first_name} {selectedUser.last_name}</span>
                    <span className="px-2 py-0.5 rounded-md bg-primary/20 text-primary text-[0.6rem] font-black uppercase">
                      {selectedUser.role}
                    </span>
                  </h4>
                  <p className="text-xs text-text-muted mt-0.5 font-medium">
                    {selectedUser.email} {selectedUser.id_number && `• Ref: ${selectedUser.id_number}`}
                  </p>
                </div>
              </div>
              <button
                type="button"
                onClick={() => setSelectedUser(null)}
                className="px-3 py-1.5 rounded-xl border border-border bg-card text-text-muted hover:text-rose-500 hover:border-rose-500/30 text-xs font-bold transition-all"
              >
                Change
              </button>
            </div>
          ) : (
            /* Search Input and Results Dropdown */
            <div className="relative" ref={searchContainerRef}>
              <div className="relative">
                <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
                <input
                  type="text"
                  placeholder={`Search ${audience === 'student' ? 'student' : 'staff member'} by name, email, or ID...`}
                  value={userSearchQuery}
                  onFocus={() => setIsDropdownOpen(true)}
                  onChange={(e) => {
                    setUserSearchQuery(e.target.value);
                    setIsDropdownOpen(true);
                  }}
                  className="w-full pl-11 pr-10 py-3.5 rounded-2xl border border-border bg-muted/30 text-text placeholder:text-text-muted text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-primary/45 focus:border-primary transition-all"
                />
                <ChevronDown size={16} className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" />
              </div>

              {/* Dropdown Menu */}
              {isDropdownOpen && (
                <div className="absolute top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-2xl z-50 max-h-60 overflow-y-auto divide-y divide-border/50 animate-in fade-in duration-150">
                  {loadingUsers ? (
                    <div className="p-4 text-center text-xs font-bold text-text-muted uppercase tracking-wider">
                      Loading users...
                    </div>
                  ) : filteredUsers.length === 0 ? (
                    <div className="p-4 text-center text-xs font-bold text-text-muted">
                      No active {audience === 'student' ? 'students' : 'staff members'} found{userSearchQuery.trim() ? ` matching "${userSearchQuery}"` : ''}
                    </div>
                  ) : (
                    filteredUsers.map((u) => (
                      <button
                        key={u.id}
                        type="button"
                        onClick={() => handleSelectUser(u)}
                        className="w-full p-3.5 text-left flex items-center justify-between hover:bg-muted/50 transition-colors group"
                      >
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg bg-muted text-text font-black flex items-center justify-center text-xs">
                            {(u.first_name || 'U')[0]}{(u.last_name || '')[0] || ''}
                          </div>
                          <div>
                            <span className="font-extrabold text-sm text-text group-hover:text-primary transition-colors block">
                              {u.first_name} {u.last_name}
                            </span>
                            <span className="text-[0.7rem] text-text-muted block">
                              {u.email} {u.id_number && `• Ref: ${u.id_number}`}
                            </span>
                          </div>
                        </div>
                        <span className="px-2.5 py-0.5 rounded-md bg-muted text-[0.6rem] font-black uppercase text-text-muted border border-border">
                          {u.role}
                        </span>
                      </button>
                    ))
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 3. Reason Free Dropdown */}
        <div className="space-y-2">
          <label htmlFor="withdrawal-reason" className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
            Reason for Withdrawal / Offboarding <span className="text-rose-500">*</span>
          </label>
          <select
            id="withdrawal-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            className="w-full px-4 py-3.5 rounded-2xl border border-border bg-muted/30 text-text font-bold text-sm focus:outline-none focus:ring-2 focus:ring-primary/45 transition-all"
          >
            {audience === 'student' ? (
              <>
                <option value="withdrawn">Withdrawn (General)</option>
                <option value="graduated">Graduated (Completed Studies)</option>
                <option value="transferred">Transferred (Other Institution)</option>
                <option value="expelled">Expelled (Disciplinary Action)</option>
                <option value="other">Other / Custom Circumstance</option>
              </>
            ) : (
              <>
                <option value="resigned">Resigned (Voluntary Departure)</option>
                <option value="terminated">Terminated (Employment End)</option>
                <option value="retired">Retired (Age / Service)</option>
                <option value="deceased">Deceased</option>
                <option value="other">Other / Custom Circumstance</option>
              </>
            )}
          </select>
        </div>

        {/* 4. Conditional Destination Field */}
        {audience === 'student' && reason === 'transferred' && (
          <div className="space-y-2 animate-in fade-in duration-200">
            <label htmlFor="transfer-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="transfer-destination"
              type="text"
              placeholder="e.g. Samuel Centenary Academy, Harare"
              value={destination}
              onChange={(e) => setDestination(e.target.value)}
              className="w-full px-4 py-3.5 rounded-2xl border border-border bg-muted/30 text-text text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-primary/45 transition-all"
            />
          </div>
        )}

        {/* 5. Effective Date Picker */}
        <div className="space-y-2">
          <label htmlFor="effective-date" className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
            Effective Date <span className="text-rose-500">*</span>
          </label>
          <div className="relative">
            <Calendar size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              id="effective-date"
              type="date"
              value={effectiveDate}
              onChange={(e) => setEffectiveDate(e.target.value)}
              className="w-full pl-11 pr-4 py-3.5 rounded-2xl border border-border bg-muted/30 text-text font-bold text-sm focus:outline-none focus:ring-2 focus:ring-primary/45 transition-all"
            />
          </div>
        </div>

        {/* 6. Withdrawal Notes */}
        <div className="space-y-2">
          <label htmlFor="withdrawal-notes" className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
            Withdrawal Notes / Official Remarks
          </label>
          <textarea
            id="withdrawal-notes"
            rows={3}
            placeholder="Provide extra context, clearance details, or memo notes..."
            value={reasonNotes}
            onChange={(e) => setReasonNotes(e.target.value)}
            className="w-full px-4 py-3 rounded-2xl 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 transition-all resize-none"
          />
        </div>

        {/* 7. Action Footer */}
        <div className="flex gap-3 pt-4 border-t border-border/60">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="flex-1 py-3.5 bg-muted hover:bg-muted/80 border border-border text-text rounded-xl font-bold text-xs uppercase tracking-widest transition-all"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={submitting || !selectedUser}
            className="flex-1 py-3.5 bg-rose-600 hover:bg-rose-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-xl font-black uppercase text-xs tracking-widest transition-all shadow-md active:scale-95 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>Executing...</span>
              </>
            ) : (
              <>
                <UserMinus size={16} />
                <span>Execute Offboard</span>
              </>
            )}
          </button>
        </div>
      </form>
    </Modal>
  );
};

export default InitiateOffboardingModal;
