import React, { useState } from 'react';
import { Trash2, Users, Tag as TagIcon } from 'lucide-react';
import { useTourStore } from '@/store/useTourStore';

export const CreateTourModal = ({ isOpen, onClose, onSuccess }: { isOpen: boolean, onClose: () => void, onSuccess: (tour: any) => void }) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [adultCount, setAdultCount] = useState(2);
  const [childCount, setChildCount] = useState(1);
  const [childDiscount, setChildDiscount] = useState(30);
  const [isLoading, setIsLoading] = useState(false);
  const createTour = useTourStore((state) => state.createTour);

  const availableTags = ['Văn hóa', 'Mạo hiểm', 'Nghỉ dưỡng', 'Thư giãn', 'Ẩm thực', 'Khám phá', 'Gia đình'];
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [customTag, setCustomTag] = useState('');

  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 res = await fetch(`/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 toggleTag = (tag: string) => {
    setSelectedTags(prev => 
      prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag]
    );
  };

  const addCustomTag = () => {
    const tag = customTag.trim();
    if (tag && !selectedTags.includes(tag)) {
      setSelectedTags([...selectedTags, tag]);
      setCustomTag('');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');
    try {
      const membersPayload = members.map((m) => {
        if (m.isManual) {
          return { displayName: m.name };
        } else {
          return { userId: m.id };
        }
      });
      const tour = await createTour({ 
        title, 
        description,
        startDate, 
        endDate, 
        members: membersPayload,
        adultCount,
        childCount,
        childDiscount,
        tags: selectedTags
      });
      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-[var(--surface)] rounded-3xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div className="p-5 border-b border-[var(--border)] flex justify-between items-center bg-[var(--background)]/50">
          <h2 className="text-xl font-bold text-[var(--text-primary)]">Tạo Tour mới</h2>
          <button onClick={onClose} className="p-2 hover:bg-[var(--background)] rounded-full transition-colors">✕</button>
        </div>

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

          <div>
            <label className="block text-sm font-bold text-[var(--text-secondary)] mb-2 flex items-center gap-2">
              <TagIcon className="w-4 h-4" /> Phân loại Tour
            </label>
            <div className="flex flex-wrap gap-2">
              {availableTags.map(tag => (
                <button
                  key={tag}
                  type="button"
                  onClick={() => toggleTag(tag)}
                  className={`px-3 py-1.5 rounded-full text-xs font-bold transition-all border ${
                    selectedTags.includes(tag) 
                      ? 'bg-blue-600 text-white border-blue-600 shadow-md shadow-blue-100' 
                      : 'bg-[var(--surface)] text-[var(--text-secondary)] border-[var(--border)] hover:border-blue-300'
                  }`}
                >
                  {tag}
                </button>
              ))}
            </div>
            <div className="flex gap-2 mt-3">
              <input
                type="text"
                value={customTag}
                onChange={(e) => setCustomTag(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addCustomTag())}
                placeholder="Thêm nhãn tùy chỉnh..."
                className="flex-1 px-3 py-2 bg-[var(--background)] border border-[var(--border)] rounded-xl text-xs outline-none focus:ring-2 focus:ring-blue-500"
              />
              <button
                type="button"
                onClick={addCustomTag}
                className="px-4 py-2 bg-blue-50 text-blue-600 rounded-xl text-xs font-bold hover:bg-blue-100 transition-all"
              >
                Thêm
              </button>
            </div>
          </div>

          <div>
            <label className="block text-sm font-bold text-[var(--text-secondary)] mb-1">Mô tả chuyến đi</label>
            <textarea
              className="w-full px-4 py-3 bg-[var(--background)] border border-[var(--border)] rounded-xl outline-none focus:ring-2 focus:ring-blue-500 resize-none text-sm"
              rows={3}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Viết vài dòng giới thiệu về hành trình..."
            />
          </div>

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

          <div className="bg-blue-50/50 p-4 rounded-2xl border border-blue-100 space-y-3">
            <div className="flex items-center gap-2 text-blue-600 mb-1">
              <Users className="w-4 h-4" />
              <span className="text-xs font-black uppercase tracking-wider">Cơ cấu đoàn & Định mức chi phí</span>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="block text-[10px] font-bold text-[var(--text-muted)] uppercase mb-1">Người lớn</label>
                <input type="number" className="w-full px-3 py-2 bg-[var(--surface)] border border-[var(--border)] rounded-xl outline-none text-sm" 
                  value={adultCount} onChange={e => setAdultCount(Number(e.target.value))} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-[var(--text-muted)] uppercase mb-1">Trẻ em</label>
                <input type="number" className="w-full px-3 py-2 bg-[var(--surface)] border border-[var(--border)] rounded-xl outline-none text-sm" 
                  value={childCount} onChange={e => setChildCount(Number(e.target.value))} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-[var(--text-muted)] uppercase mb-1">Giảm trẻ em %</label>
                <input type="number" className="w-full px-3 py-2 bg-[var(--surface)] border border-[var(--border)] rounded-xl outline-none text-sm" 
                  value={childDiscount} onChange={e => setChildDiscount(Number(e.target.value))} />
              </div>
            </div>
            <p className="text-[10px] text-blue-400 italic font-medium">* Dùng để tính toán đơn giá bình quân trong báo cáo chi phí.</p>
          </div>

          <div className="space-y-2">
            <label className="block text-sm font-bold text-[var(--text-secondary)]">Thành viên tham gia ({members.length})</label>
            {members.length > 0 && (
              <div className="flex flex-wrap gap-3 mb-3 p-3 bg-[var(--background)] rounded-2xl border border-[var(--border)]">
                {members.map((m) => {
                  const initial = m.name?.charAt(0) || '?';
                  return (
                    <div key={m.id} className="flex flex-col items-center gap-1">
                      <div className="relative">
                        <div className="w-10 h-10 rounded-full bg-blue-100 border border-blue-200 flex items-center justify-center text-blue-700 font-bold text-sm overflow-hidden">
                          {initial}
                        </div>
                        <button
                          type="button"
                          onClick={() => removeMember(m.id)}
                          className="absolute -top-1 -right-1 w-4 h-4 bg-gray-400 hover:bg-red-600 rounded-full flex items-center justify-center text-white"
                          aria-label="Remove item"
                        >
                          <Trash2 size={10} />
                        </button>
                      </div>
                      <span className="text-[10px] font-semibold text-[var(--text-secondary)] max-w-[72px] truncate">{m.name}</span>
                    </div>
                  );
                })}
              </div>
            )}

            <div className="relative">
              <input
                className="w-full px-4 py-3 bg-[var(--background)] border border-[var(--border)] rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-sm font-bold text-[var(--text-primary)]"
                placeholder="Tìm email hoặc nhập tên thành viên ngoài hệ thống..."
                value={query}
                onChange={(e) => searchUsers(e.target.value)}
              />
              {(results.length > 0 || query.trim()) && (
                <div className="absolute bottom-full mb-2 left-0 right-0 bg-[var(--surface)] border border-[var(--border)] rounded-2xl shadow-xl z-20 max-h-48 overflow-y-auto p-2 space-y-1">
                  {query.trim() && (
                    <button
                      type="button"
                      onClick={() => {
                        const name = query.trim();
                        setMembers((prev) => (prev.some((m) => m.name.toLowerCase() === name.toLowerCase()) ? prev : [...prev, { id: `manual-${Date.now()}`, name, isManual: true }]));
                        setQuery('');
                        setResults([]);
                      }}
                      className="w-full text-left px-3 py-2 text-sm hover:bg-[var(--background)] rounded-xl text-blue-600 font-bold flex items-center gap-2"
                    >
                      <span className="flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-600 text-sm font-black">+</span>
                      <span>Thêm thành viên ngoài hệ thống: "{query.trim()}"</span>
                    </button>
                  )}
                  {results.filter(u => !members.some(m => m.id === u.id)).map((u) => (
                    <button
                      key={u.id}
                      type="button"
                      onClick={() => confirmAddMember(u)}
                      className="w-full text-left px-3 py-2 text-sm hover:bg-[var(--background)] rounded-xl flex flex-col"
                    >
                      <span className="font-bold text-[var(--text-primary)]">{u.name || 'Chưa đặt tên'}</span>
                      <span className="text-xs text-[var(--text-muted)]">{u.email}</span>
                    </button>
                  ))}
                </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>
  );
};
