import React, { useState, useEffect } from 'react';
import { X, Search, UserPlus, Loader2, Shield, ShieldAlert } from 'lucide-react';

interface AddMemberModalProps {
  isOpen: boolean;
  onClose: () => void;
  tourId: string;
}

export const AddMemberModal: React.FC<AddMemberModalProps> = ({ isOpen, onClose, tourId }) => {
  const [query, setQuery] = useState('');
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const [role, setRole] = useState<'OWNER' | 'MANAGER' | 'MEMBER' | 'MEMBER_NO_FINANCE' | 'VIEWER_ONLY'>('MEMBER');
  const [submitting, setSubmitting] = useState(false);
  const [fetchError, setFetchError] = useState('');
  const [submitError, setSubmitError] = useState('');

  const fetchUsers = async () => {
    setLoading(true);
    setFetchError('');
    try {
      const API_BASE = `http://${window.location.hostname}:3001`;
      const res = await fetch(`${API_BASE}/api/v1/users?q=${encodeURIComponent(query)}`, {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      });
      if (!res.ok) throw new Error('Không thể tải danh sách người dùng');
      const data = await res.json();
      setUsers(data);
    } catch (err: any) {
      setFetchError(err.message || 'Không thể tải danh sách người dùng');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!isOpen) return;
    fetchUsers();
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) {
      setQuery('');
      setSelectedUser(null);
      setRole('MEMBER');
      setFetchError('');
    }
  }, [isOpen]);

  const handleAdd = async () => {
    if (!selectedUser) return;
    setSubmitting(true);
    try {
      const API_BASE = `http://${window.location.hostname}:3001`;
      const res = await fetch(`${API_BASE}/api/v1/tours/${tourId}/members`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ userId: selectedUser, role }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.message || 'Thêm thành viên thất bại');
      }
      onClose();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[2000] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-gray-900/60 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-md bg-white rounded-3xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div className="p-5 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
          <div>
            <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <UserPlus className="w-5 h-5 text-blue-600" /> Thêm thành viên
            </h2>
            <p className="text-xs text-gray-500">Chọn người dùng và phân quyền cho tour này.</p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-full transition-colors">
            <X className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        <div className="p-5 space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              className="w-full pl-9 pr-4 py-2.5 bg-gray-50 border border-gray-100 rounded-xl outline-none text-sm"
              placeholder="Tìm theo tên hoặc email..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onBlur={fetchUsers}
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-xs font-bold text-gray-700 ml-1">Phân quyền</label>
            <select
              className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none text-sm"
              value={role}
              onChange={(e) => setRole(e.target.value as any)}
            >
              <option value="OWNER">OWNER</option>
              <option value="MANAGER">MANAGER</option>
              <option value="MEMBER">MEMBER</option>
              <option value="MEMBER_NO_FINANCE">MEMBER_NO_FINANCE</option>
              <option value="VIEWER_ONLY">VIEWER_ONLY</option>
            </select>
          </div>

          <div className="space-y-2">
            {fetchError && (
              <div className="p-3 bg-red-50 text-red-600 rounded-xl text-xs font-bold border border-red-100">
                {fetchError}
              </div>
            )}
            {loading ? (
              <div className="flex justify-center py-10"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
            ) : (
              <div className="space-y-2 max-h-[40vh] overflow-y-auto pr-1">
                {users.map((u) => {
                  const isSelected = selectedUser === u.id;
                  return (
                    <button
                      key={u.id}
                      onClick={() => setSelectedUser(u.id)}
                      className={`w-full flex items-center gap-3 p-3 rounded-2xl border transition-all ${
                        isSelected ? 'border-blue-500 bg-blue-50/60' : 'border-gray-100 hover:border-blue-200'
                      }`}
                    >
                      <div className="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 font-bold">
                        {u.name?.charAt(0) || '?'}
                      </div>
                      <div className="flex-1 text-left">
                        <div className="text-sm font-bold text-gray-900">{u.name || 'Chưa đặt tên'}</div>
                        <div className="text-[11px] text-gray-500">{u.email}</div>
                        <div className="text-[11px] text-gray-400">{u.phone || ''} {u.address ? `• ${u.address}` : ''}</div>
                      </div>
                      <div className="flex items-center gap-1 text-[10px] font-bold text-gray-500">
                        {u.isAdmin ? (
                          <span className="px-2 py-1 bg-purple-50 text-purple-600 rounded-md border border-purple-100">ADMIN</span>
                        ) : (
                          <span className="px-2 py-1 bg-gray-50 text-gray-500 rounded-md border border-gray-100">USER</span>
                        )}
                        {isSelected && <Shield className="w-3 h-3 text-blue-600" />}
                      </div>
                    </button>
                  );
                })}
                {!loading && users.length === 0 && (
                  <div className="text-center py-8 text-sm text-gray-500">Không tìm thấy người dùng phù hợp</div>
                )}
              </div>
            )}
          </div>
        </div>

        <div className="p-5 border-t border-gray-100 flex justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2.5 rounded-xl text-sm font-bold text-gray-600 hover:bg-gray-100 transition-colors">
            Hủy
          </button>
          <button
            disabled={!selectedUser || submitting}
            onClick={handleAdd}
            className="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded-xl text-sm font-bold transition-all"
          >
            {submitting ? 'Đang thêm...' : 'Thêm vào tour'}
          </button>
        </div>
      </div>
    </div>
  );
};
