import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { motion, AnimatePresence } from "framer-motion";
import ConfirmModal from "../components/ConfirmModal";
import useModalLock from "../hooks/useModalLock";

import apiFetch from "../utils/api";
import FormField from "../components/FormField";
import {
  warehouseLocationListOptions,
  type WarehouseLocation,
} from "../lib/queries/warehouse";

const API_BASE = "/api/admin/warehouse/locations";

interface LocationForm {
  code: string;
  name: string;
  description: string;
}

export default function WarehouseLocations() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const queryClient = useQueryClient();

  const { data: locations = [], isPending } = useQuery(
    warehouseLocationListOptions(),
  );

  const [showModal, setShowModal] = useState(false);
  const [editingLocation, setEditingLocation] =
    useState<WarehouseLocation | null>(null);
  const [form, setForm] = useState<LocationForm>({
    code: "",
    name: "",
    description: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    location: WarehouseLocation | null;
  }>({ show: false, location: null });

  useModalLock(showModal);

  if (!hasPermission("warehouse.manage")) return <Forbidden />;

  const openCreateModal = () => {
    setEditingLocation(null);
    setForm({
      code: "",
      name: "",
      description: "",
    });
    setErrors({});
    setShowModal(true);
  };

  const openEditModal = (location: WarehouseLocation) => {
    setEditingLocation(location);
    setForm({
      code: location.code,
      name: location.name,
      description: location.description || "",
    });
    setErrors({});
    setShowModal(true);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (!form.code.trim()) newErrors.code = "Zadejte kód umístění";
    if (!form.name.trim()) newErrors.name = "Zadejte název umístění";
    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) return;

    try {
      const url = editingLocation
        ? `${API_BASE}/${editingLocation.id}`
        : API_BASE;
      const method = editingLocation ? "PUT" : "POST";

      const response = await apiFetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });

      const result = await response.json();

      if (result.success) {
        setShowModal(false);
        queryClient.invalidateQueries({ queryKey: ["warehouse", "locations"] });
        queryClient.invalidateQueries({ queryKey: ["warehouse"] });
        alert.success(result.message);
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.location) return;

    try {
      const response = await apiFetch(
        `${API_BASE}/${deleteConfirm.location.id}`,
        {
          method: "DELETE",
        },
      );

      const result = await response.json();

      if (result.success) {
        setDeleteConfirm({ show: false, location: null });
        queryClient.invalidateQueries({ queryKey: ["warehouse", "locations"] });
        queryClient.invalidateQueries({ queryKey: ["warehouse"] });
        alert.success(result.message);
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    }
  };

  const toggleActive = async (location: WarehouseLocation) => {
    try {
      const response = await apiFetch(`${API_BASE}/${location.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ is_active: !location.is_active }),
      });

      const result = await response.json();

      if (result.success) {
        queryClient.invalidateQueries({ queryKey: ["warehouse", "locations"] });
        queryClient.invalidateQueries({ queryKey: ["warehouse"] });
        alert.success(
          location.is_active
            ? "Umístění bylo deaktivováno"
            : "Umístění bylo aktivováno",
        );
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    }
  };

  if (isPending) {
    return (
      <div className="admin-loading">
        <div className="admin-spinner" />
      </div>
    );
  }

  return (
    <div>
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div>
          <h1 className="admin-page-title">Umístění skladu</h1>
        </div>
        <div className="admin-page-actions">
          <button
            onClick={openCreateModal}
            className="admin-btn admin-btn-primary"
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <line x1="12" y1="5" x2="12" y2="19" />
              <line x1="5" y1="12" x2="19" y2="12" />
            </svg>
            Přidat umístění
          </button>
        </div>
      </motion.div>

      <motion.div
        className="admin-card"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.06 }}
      >
        <div className="admin-card-body">
          {locations.length === 0 && (
            <div className="admin-empty-state">
              <div className="admin-empty-icon">
                <svg
                  width="28"
                  height="28"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
                  <circle cx="12" cy="10" r="3" />
                </svg>
              </div>
              <p>Zatím nejsou žádná umístění.</p>
              <button
                onClick={openCreateModal}
                className="admin-btn admin-btn-primary"
              >
                Přidat první umístění
              </button>
            </div>
          )}
          {locations.length > 0 && (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Kód</th>
                    <th>Název</th>
                    <th>Popis</th>
                    <th>Stav</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {locations.map((location) => (
                    <tr
                      key={location.id}
                      className={
                        !location.is_active ? "admin-table-row-inactive" : ""
                      }
                    >
                      <td className="admin-mono fw-500">{location.code}</td>
                      <td>{location.name}</td>
                      <td>{location.description || "—"}</td>
                      <td>
                        <button
                          onClick={() => toggleActive(location)}
                          className={`admin-badge ${location.is_active ? "admin-badge-active" : "admin-badge-inactive"}`}
                        >
                          {location.is_active ? "Aktivní" : "Neaktivní"}
                        </button>
                      </td>
                      <td>
                        <div className="admin-table-actions">
                          <button
                            onClick={() => openEditModal(location)}
                            className="admin-btn-icon"
                            title="Upravit"
                            aria-label="Upravit"
                          >
                            <svg
                              width="18"
                              height="18"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                            </svg>
                          </button>
                          <button
                            onClick={() =>
                              setDeleteConfirm({ show: true, location })
                            }
                            className="admin-btn-icon danger"
                            title="Smazat"
                            aria-label="Smazat"
                          >
                            <svg
                              width="18"
                              height="18"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <polyline points="3 6 5 6 21 6" />
                              <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                            </svg>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </motion.div>

      {/* Add/Edit Modal */}
      <AnimatePresence>
        {showModal && (
          <motion.div
            className="admin-modal-overlay"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <div
              className="admin-modal-backdrop"
              onClick={() => setShowModal(false)}
            />
            <motion.div
              className="admin-modal"
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              transition={{ duration: 0.2 }}
            >
              <div className="admin-modal-header">
                <h2 className="admin-modal-title">
                  {editingLocation ? "Upravit umístění" : "Přidat umístění"}
                </h2>
              </div>

              <div className="admin-modal-body">
                <div className="admin-form">
                  <div className="admin-form-row">
                    <FormField label="Kód" error={errors.code} required>
                      <input
                        type="text"
                        value={form.code}
                        onChange={(e) => {
                          setForm({
                            ...form,
                            code: e.target.value.toUpperCase(),
                          });
                          setErrors((prev) => ({
                            ...prev,
                            code: "",
                          }));
                        }}
                        className="admin-form-input"
                        placeholder="A-01"
                        aria-invalid={!!errors.code}
                      />
                    </FormField>

                    <FormField label="Název" error={errors.name} required>
                      <input
                        type="text"
                        value={form.name}
                        onChange={(e) => {
                          setForm({ ...form, name: e.target.value });
                          setErrors((prev) => ({
                            ...prev,
                            name: "",
                          }));
                        }}
                        className="admin-form-input"
                        placeholder="Regál A, polička 1"
                        aria-invalid={!!errors.name}
                      />
                    </FormField>
                  </div>

                  <FormField label="Popis">
                    <textarea
                      value={form.description}
                      onChange={(e) =>
                        setForm({
                          ...form,
                          description: e.target.value,
                        })
                      }
                      className="admin-form-input"
                      rows={3}
                      placeholder="Volitelný popis umístění"
                    />
                  </FormField>
                </div>
              </div>

              <div className="admin-modal-footer">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="admin-btn admin-btn-secondary"
                >
                  Zrušit
                </button>
                <button
                  type="button"
                  onClick={handleSubmit}
                  className="admin-btn admin-btn-primary"
                >
                  Uložit
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Delete Confirmation */}
      <ConfirmModal
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, location: null })}
        onConfirm={handleDelete}
        title="Smazat umístění"
        message={
          deleteConfirm.location
            ? `Opravdu chcete smazat umístění "${deleteConfirm.location.code} - ${deleteConfirm.location.name}"? Pokud umístění obsahuje zásoby, nelze jej smazat.`
            : ""
        }
        confirmText="Smazat"
        confirmVariant="danger"
      />
    </div>
  );
}
