import React, { useState } from 'react';
import { Trash2 } from 'lucide-react';
import { useTourStore } from './useTourStore.js';

export const CreateTourModal = ({ isOpen, onClose, onSuccess }: { isOpen: boolean, onClose: () => void, onSuccess: (tour: any) => void }) => {
  const [title, setTitle] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const createTour = useTourStore((state) => state.createTour);

  const [members, setMembers] = useState<any[]>([]);
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<any[]>([]);
  const [error, setError] = useState('');

  if (!isOpen) return null;

  const searchUsers = async (value: string) => {
    setQuery(value);
    if (!value.trim()) {
      setResults([]);
      return;
    }
    try {
      const API_BASE = `http://${window.location.hostname}:3001`;
      const res = await fetch(`${API_BASE}/api/v1/users?q=${encodeURIComponent(value)}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
      });
      if (!res.ok) throw new Error('Không thể tải người dùng');
      const data = await res.json();
      setResults(Array.isArray(data) ? data : []);
    } catch (e: any) {
      setResults([]);
      setError(e.message || 'Không thể tải người dùng');
    }
  };

  const confirmAddMember = (user: any) => {
    setMembers((prev) => (prev.some((m) => m.id === user.id) ? prev : [...prev, user]));
    setQuery('');
    setResults([]);
    setError('');
  };

  const removeMember = (userId: string) => {
    setMembers((prev) => prev.filter((m) => m.id !== userId));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');
    try {
      const memberIds = members.map((m) => m.id);
      const tour = await createTour({ title, startDate, endDate, memberIds });
      onSuccess(tour);
      onClose();
    } catch (e: any) {
      setError(e.message || 'Lỗi khi tạo tour');
    } finally {
      setIsLoading(false);
    }
  };

  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 p-6">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-gray-900">Tạo Tour mới</h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">✕</button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Tên Tour</label>
            <input
              required
              className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="VD: Khám phá Đà Lạt"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">Bắt đầu</label>
              <input
                type="date"
                className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
            </div>
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">Kết thúc</label>
              <input
                type="date"
                className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-bold text-gray-700 mb-2">Thành viên tham gia</label>
            <div className="flex flex-wrap gap-3">
              {members.map((m) => (
                <div key={m.id} className="relative">
                  <div className="w-12 h-12 rounded-full bg-blue-100 border border-blue-200 flex items-center justify-center text-blue-700 font-bold text-sm overflow-hidden">
                    {m.name}
                  </div>
                  <button
                    type="button"
                    onClick={() => removeMember(m.id)}
                    className="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-gray-500 hover:bg-red-600 text-white flex items-center justify-center transition-colors"
                    aria-label="Remove item"
                  >
                    <Trash2 size={12} />
                  </button>
                  <div className="text-[10px] text-center mt-1 max-w-[70px] truncate">{m.name}</div>
                </div>
              ))}

              <div className="relative">
                <input
                  className="w-36 px-2 py-1 text-sm border border-gray-200 rounded-lg outline-none"
                  placeholder="Tìm email..."
                  value={query}
                  onChange={(e) => searchUsers(e.target.value)}
                />
                {results.length > 0 && (
                  <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-100 rounded-xl shadow-lg z-10 max-h-60 overflow-y-auto">
                    {results.map((u) => (
                      <button
                        key={u.id}
                        type="button"
                        onClick={() => confirmAddMember(u)}
                        className="w-full text-left px-3 py-2 text-sm hover:bg-blue-50"
                      >
                        <span className="font-bold text-gray-900">{u.name}</span>
                        <span className="block text-xs text-gray-500">{u.email}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
            {error && <p className="text-xs text-red-600 mt-2">{error}</p>}
          </div>

          <button
            type="submit"
            disabled={isLoading}
            className="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-2xl shadow-lg transition-all flex items-center justify-center gap-2"
          >
            {isLoading ? 'Đang tạo...' : 'Xác nhận tạo Tour'}
          </button>
        </form>
      </div>
    </div>
  );
};
