import { useEffect, useState } from 'react';
import AdminLayout from '../../components/AdminLayout';
import { getAreas, createArea, updateArea, deleteArea } from '../../utils/api';

const AdminAreas = () => {
  const [areas, setAreas] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState(null);
  const [formData, setFormData] = useState({
    province: '',
    cities: []
  });
  const [cityInput, setCityInput] = useState('');

  useEffect(() => {
    loadAreas();
  }, []);

  const loadAreas = async () => {
    try {
      const response = await getAreas();
      setAreas(response.data);
    } catch (error) {
      console.error('Error loading areas:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await updateArea(editingId, formData);
      } else {
        await createArea(formData);
      }
      await loadAreas();
      resetForm();
    } catch (error) {
      alert('Failed to save area');
    }
  };

  const handleEdit = (area) => {
    setEditingId(area.id);
    setFormData({
      province: area.province,
      cities: area.cities
    });
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this area?')) return;
    try {
      await deleteArea(id);
      await loadAreas();
    } catch (error) {
      alert('Failed to delete area');
    }
  };

  const addCity = () => {
    if (cityInput.trim()) {
      setFormData({
        ...formData,
        cities: [...formData.cities, cityInput.trim()]
      });
      setCityInput('');
    }
  };

  const removeCity = (index) => {
    setFormData({
      ...formData,
      cities: formData.cities.filter((_, i) => i !== index)
    });
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData({ province: '', cities: [] });
    setCityInput('');
  };

  if (loading) {
    return <AdminLayout><div className="text-center py-20">Loading...</div></AdminLayout>;
  }

  return (
    <AdminLayout>
      <h1 className="text-3xl font-extrabold text-gray-900 mb-8">Manage Service Areas</h1>

      <div className="grid md:grid-cols-2 gap-8">
        {/* Form */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-bold mb-6">{editingId ? 'Edit Area' : 'Add New Area'}</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Province</label>
              <input 
                type="text"
                value={formData.province}
                onChange={(e) => setFormData({...formData, province: e.target.value})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Cities</label>
              <div className="flex gap-2 mb-3">
                <input 
                  type="text"
                  value={cityInput}
                  onChange={(e) => setCityInput(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addCity())}
                  className="flex-1 px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                  placeholder="Add city name"
                />
                <button type="button" onClick={addCity} className="bg-blue-600 text-white px-6 py-3 rounded-xl hover:bg-blue-700">
                  Add
                </button>
              </div>
              <div className="flex flex-wrap gap-2">
                {formData.cities.map((city, index) => (
                  <span key={index} className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm flex items-center gap-2">
                    {city}
                    <button type="button" onClick={() => removeCity(index)} className="text-blue-900 hover:text-red-600">
                      ×
                    </button>
                  </span>
                ))}
              </div>
            </div>
            <div className="flex gap-3">
              <button type="submit" disabled={formData.cities.length === 0} className="bg-blue-600 text-white px-6 py-3 rounded-xl font-bold hover:bg-blue-700 transition disabled:opacity-50">
                {editingId ? 'Update' : 'Add'}
              </button>
              {editingId && (
                <button type="button" onClick={resetForm} className="bg-gray-200 px-6 py-3 rounded-xl font-bold hover:bg-gray-300 transition">
                  Cancel
                </button>
              )}
            </div>
          </form>
        </div>

        {/* List */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-bold mb-6">Current Areas</h2>
          <div className="space-y-4">
            {areas.map((area) => (
              <div key={area.id} className="border border-gray-200 rounded-xl p-4">
                <div className="flex items-start justify-between mb-3">
                  <h3 className="font-bold text-gray-900 text-lg">{area.province}</h3>
                  <div className="flex gap-2">
                    <button onClick={() => handleEdit(area)} className="text-blue-600 hover:text-blue-700 font-semibold">
                      Edit
                    </button>
                    <button onClick={() => handleDelete(area.id)} className="text-red-600 hover:text-red-700 font-semibold">
                      Delete
                    </button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {area.cities.map((city, idx) => (
                    <span key={idx} className="bg-gray-100 text-gray-700 px-3 py-1 rounded-full text-sm">
                      {city}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdminAreas;
