import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import {
  warehouseCategoryListOptions,
  type WarehouseCategory,
} from "../lib/queries/warehouse";
import { useApiMutation } from "../lib/queries/mutations";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  PageHeader,
  PageEnter,
  EmptyState,
  LoadingState,
  type DataColumn,
} from "../ui";

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

interface CategoryForm {
  name: string;
  description: string;
  sort_order: number;
}

const PlusIcon = (
  <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>
);
const EditIcon = (
  <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>
);
const DeleteIcon = (
  <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>
);

export default function WarehouseCategories() {
  const alert = useAlert();
  const { hasPermission } = useAuth();

  const { data: categories = [], isPending } = useQuery(
    warehouseCategoryListOptions(),
  );

  const [showModal, setShowModal] = useState(false);
  const [editingCategory, setEditingCategory] =
    useState<WarehouseCategory | null>(null);
  const [form, setForm] = useState<CategoryForm>({
    name: "",
    description: "",
    sort_order: 0,
  });

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

  const submitMutation = useApiMutation<CategoryForm, void>({
    url: () =>
      editingCategory ? `${API_BASE}/${editingCategory.id}` : API_BASE,
    method: () => (editingCategory ? "PUT" : "POST"),
    invalidate: ["warehouse"],
    onSuccess: () => {
      setShowModal(false);
      alert.success(
        editingCategory
          ? "Kategorie byla upravena"
          : "Kategorie byla vytvořena",
      );
    },
  });

  const deleteMutation = useApiMutation<number, void>({
    url: (id) => `${API_BASE}/${id}`,
    method: () => "DELETE",
    invalidate: ["warehouse"],
    onSuccess: () => {
      setDeleteConfirm({ show: false, category: null });
      alert.success("Kategorie byla smazána");
    },
  });

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

  const openCreateModal = () => {
    setEditingCategory(null);
    setForm({
      name: "",
      description: "",
      sort_order: 0,
    });
    setErrors({});
    setShowModal(true);
  };

  const openEditModal = (category: WarehouseCategory) => {
    setEditingCategory(category);
    setForm({
      name: category.name,
      description: category.description || "",
      sort_order: category.sort_order,
    });
    setErrors({});
    setShowModal(true);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (!form.name.trim()) newErrors.name = "Zadejte název kategorie";
    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) return;

    try {
      await submitMutation.mutateAsync(form);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.category) return;
    try {
      await deleteMutation.mutateAsync(deleteConfirm.category.id);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  if (isPending) {
    return <LoadingState />;
  }

  const total = categories.length;
  const subtitle = `${total} ${
    total === 1
      ? "kategorie"
      : total >= 2 && total <= 4
        ? "kategorie"
        : "kategorií"
  }`;

  const columns: DataColumn<WarehouseCategory>[] = [
    {
      key: "name",
      header: "Název",
      width: "35%",
      bold: true,
      render: (c) => c.name,
    },
    {
      key: "description",
      header: "Popis",
      width: "40%",
      render: (c) => c.description || "—",
    },
    {
      key: "sort_order",
      header: "Pořadí",
      width: "15%",
      mono: true,
      render: (c) => String(c.sort_order),
    },
    {
      key: "actions",
      header: "Akce",
      width: "10%",
      align: "right",
      render: (c) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => openEditModal(c)}
            aria-label="Upravit"
            title="Upravit"
          >
            {EditIcon}
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => setDeleteConfirm({ show: true, category: c })}
            aria-label="Smazat"
            title="Smazat"
          >
            {DeleteIcon}
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Kategorie skladu"
        subtitle={subtitle}
        actions={
          <Button startIcon={PlusIcon} onClick={openCreateModal}>
            Přidat kategorii
          </Button>
        }
      />

      <Card>
        <DataTable<WarehouseCategory>
          columns={columns}
          rows={categories}
          rowKey={(c) => c.id}
          empty={
            <EmptyState
              title="Zatím nejsou žádné kategorie."
              action={
                <Button startIcon={PlusIcon} onClick={openCreateModal}>
                  Přidat první kategorii
                </Button>
              }
            />
          }
        />
      </Card>

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={editingCategory ? "Upravit kategorii" : "Přidat kategorii"}
        loading={submitMutation.isPending}
      >
        <Field label="Název" required error={errors.name}>
          <TextField
            value={form.name}
            error={!!errors.name}
            onChange={(e) => {
              setForm({ ...form, name: e.target.value });
              setErrors((prev) => ({ ...prev, name: "" }));
            }}
            placeholder="Název kategorie"
          />
        </Field>

        <Field label="Popis">
          <TextField
            multiline
            minRows={3}
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
            placeholder="Volitelný popis kategorie"
          />
        </Field>

        <Field label="Pořadí řazení">
          <TextField
            type="number"
            value={String(form.sort_order)}
            onChange={(e) => {
              const n = Number(e.target.value);
              setForm({
                ...form,
                sort_order: Number.isFinite(n) ? n : 0,
              });
            }}
            inputProps={{ min: 0 }}
          />
        </Field>
      </Modal>

      {/* Delete Confirmation */}
      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, category: null })}
        onConfirm={handleDelete}
        title="Smazat kategorii"
        message={
          deleteConfirm.category
            ? `Opravdu chcete smazat kategorii "${deleteConfirm.category.name}"?`
            : ""
        }
        confirmText="Smazat"
        confirmVariant="danger"
        loading={deleteMutation.isPending}
      />
    </PageEnter>
  );
}
