import { useEffect, useState } from "react";
import { createStore, deleteStore, getAllStores, updateStore } from "../../api/stores";
import useActionToast from "../../hooks/useActionToast";
import getApiErrorMessage from "../../lib/getApiErrorMessage";
import "../../styles/components/admin/StoreManagement.css";

export default function StoreManagement() {
  const toast = useActionToast();
  const [stores, setStores] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingStore, setEditingStore] = useState(null);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    zones: []
  });
  const [newZone, setNewZone] = useState("");

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

  const loadStores = async () => {
    setLoading(true);
    try {
      const response = await getAllStores();
      setStores(response.data);
    } catch (error) {
      console.error("Failed to load stores:", error);
      const message = getApiErrorMessage(error, "Failed to load stores");
      toast.error("Load stores failed", `Load stores failed: ${message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (e) => {
    e.preventDefault();
    if (!formData.name.trim()) return;

    try {
      const zonesJson = formData.zones.length > 0 ? JSON.stringify(formData.zones) : null;
      await createStore(formData.name, zonesJson);
      await loadStores();
      toast.success("Created store", `Created store ${formData.name.trim()}`);
      setShowCreateForm(false);
      setFormData({ name: "", zones: [] });
      setNewZone("");
    } catch (error) {
      console.error("Failed to create store:", error);
      const message = getApiErrorMessage(error, "Failed to create store");
      toast.error("Create store failed", `Create store failed: ${message}`);
    }
  };

  const handleUpdate = async (e) => {
    e.preventDefault();
    if (!editingStore || !formData.name.trim()) return;

    try {
      const zonesJson = formData.zones.length > 0 ? JSON.stringify(formData.zones) : null;
      await updateStore(editingStore.id, formData.name, zonesJson);
      await loadStores();
      toast.success("Updated store", `Updated store ${formData.name.trim()}`);
      setEditingStore(null);
      setFormData({ name: "", zones: [] });
      setNewZone("");
    } catch (error) {
      console.error("Failed to update store:", error);
      const message = getApiErrorMessage(error, "Failed to update store");
      toast.error("Update store failed", `Update store failed: ${message}`);
    }
  };

  const handleDelete = async (storeId, storeName) => {
    if (!confirm(`Delete store "${storeName}"? This cannot be undone.`)) return;

    try {
      await deleteStore(storeId);
      await loadStores();
      toast.success("Deleted store", `Deleted store ${storeName}`);
    } catch (error) {
      console.error("Failed to delete store:", error);
      const message = getApiErrorMessage(error, "Failed to delete store");
      toast.error("Delete store failed", `Delete store failed: ${message}`);
    }
  };

  const startEdit = (store) => {
    console.log('Starting edit for store:', store);
    setEditingStore(store);
    let zones = [];
    if (store.default_zones) {
      try {
        let parsed = typeof store.default_zones === 'string'
          ? JSON.parse(store.default_zones)
          : store.default_zones;

        // Handle both formats: direct array or object with zones property
        if (Array.isArray(parsed)) {
          zones = parsed;
        } else if (parsed && Array.isArray(parsed.zones)) {
          zones = parsed.zones;
        }
      } catch (e) {
        console.error('Failed to parse zones:', e);
        zones = [];
      }
    }
    console.log('Parsed zones:', zones);
    setFormData({
      name: store.name,
      zones: zones
    });
    setShowCreateForm(false);
  };

  const cancelEdit = () => {
    setEditingStore(null);
    setFormData({ name: "", zones: [] });
    setNewZone("");
  };

  const startCreate = () => {
    setShowCreateForm(true);
    setEditingStore(null);
    setFormData({ name: "", zones: [] });
    setNewZone("");
  };

  const addZone = () => {
    const zone = newZone.trim();
    if (!zone) return;
    if (formData.zones.includes(zone)) {
      alert("Zone already exists");
      return;
    }
    setFormData({ ...formData, zones: [...formData.zones, zone] });
    setNewZone("");
  };

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

  const parseZones = (defaultZones) => {
    if (!defaultZones) return [];
    try {
      let parsed = typeof defaultZones === 'string' ? JSON.parse(defaultZones) : defaultZones;

      // Handle both formats: direct array or object with zones property
      if (Array.isArray(parsed)) {
        return parsed;
      } else if (parsed && Array.isArray(parsed.zones)) {
        return parsed.zones;
      }
      return [];
    } catch (e) {
      return [];
    }
  };

  return (
    <div className="store-management">
      <div className="store-management-header">
        <h2>Store Management</h2>
        {!showCreateForm && !editingStore && (
          <button onClick={startCreate} className="btn-primary">
            + Create Store
          </button>
        )}
      </div>

      {/* Create/Edit Form */}
      {(showCreateForm || editingStore) && (
        <div className="store-form-card">
          <h3>{editingStore ? "Edit Store" : "Create New Store"}</h3>
          <form onSubmit={editingStore ? handleUpdate : handleCreate}>
            <div className="form-group">
              <label htmlFor="storeName">Store Name *</label>
              <input
                id="storeName"
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="e.g., Costco Richmond"
                required
                autoFocus
              />
            </div>

            <div className="form-group">
              <label htmlFor="defaultZones">Default Zones</label>
              <div className="zone-input-container">
                <input
                  id="zoneInput"
                  type="text"
                  value={newZone}
                  onChange={(e) => setNewZone(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addZone())}
                  placeholder="Enter zone name and press Enter or click Add"
                />
                <button
                  type="button"
                  onClick={addZone}
                  className="btn-secondary btn-small"
                >
                  Add Zone
                </button>
              </div>
              {formData.zones.length > 0 && (
                <div className="zones-list">
                  {formData.zones.map((zone, index) => (
                    <div key={index} className="zone-chip">
                      <span>{zone}</span>
                      <button
                        type="button"
                        onClick={() => removeZone(index)}
                        className="zone-remove"
                        aria-label="Remove zone"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              )}
              <p className="form-hint">
                Add zones that will be used for organizing items in this store
              </p>
            </div>

            <div className="form-actions">
              <button
                type="button"
                onClick={editingStore ? cancelEdit : () => setShowCreateForm(false)}
                className="btn-secondary"
              >
                Cancel
              </button>
              <button type="submit" className="btn-primary">
                {editingStore ? "Update Store" : "Create Store"}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Stores List */}
      <div className="stores-grid">
        {loading ? (
          <p>Loading stores...</p>
        ) : stores.length === 0 ? (
          <p className="empty-message">No stores found. Create one to get started.</p>
        ) : (
          stores.map((store) => (
            <div key={store.id} className="store-admin-card">
              <div className="store-admin-info">
                <h3>{store.name}</h3>
                {store.default_zones && parseZones(store.default_zones).length > 0 && (
                  <div className="store-zones-display">
                    <p className="zones-label">Default Zones:</p>
                    <div className="zones-list-display">
                      {parseZones(store.default_zones).map((zone, idx) => (
                        <span key={idx} className="zone-badge">{zone}</span>
                      ))}
                    </div>
                  </div>
                )}
                <p className="store-meta">ID: {store.id}</p>
              </div>
              <div className="store-admin-actions">
                <button
                  onClick={() => startEdit(store)}
                  className="btn-secondary btn-small"
                >
                  Edit
                </button>
                <button
                  onClick={() => handleDelete(store.id, store.name)}
                  className="btn-danger btn-small"
                >
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
