import { useState, useId, useRef } from "react";
import { useNavigate, Link as RouterLink } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import ItemPicker from "../components/warehouse/ItemPicker";
import {
  warehouseLocationListOptions,
  type WarehouseLocation,
} from "../lib/queries/warehouse";
import { useApiMutation } from "../lib/queries/mutations";
import { Button, Card, TextField, Select, Field, PageEnter } from "../ui";

interface InventoryItem {
  key: string;
  item_id: number | null;
  location_id: number | null;
  actual_qty: number;
}

function parseDecimal(raw: string): number {
  const cleaned = raw.replace(/[eE+\-]/g, "");
  const n = Number(cleaned);
  return Number.isFinite(n) ? n : 0;
}

const BackIcon = (
  <svg
    width="20"
    height="20"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M19 12H5M12 19l-7-7 7-7" />
  </svg>
);

const RemoveIcon = (
  <svg
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <line x1="18" y1="6" x2="6" y2="18" />
    <line x1="6" y1="6" x2="18" y2="18" />
  </svg>
);

const PlusIcon = (
  <svg
    width="16"
    height="16"
    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>
);

export default function WarehouseInventoryForm() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const navigate = useNavigate();

  const baseId = useId();
  const counterRef = useRef(0);
  const nextKey = () => `${baseId}-item-${counterRef.current++}`;

  const [items, setItems] = useState<InventoryItem[]>([]);
  const [notes, setNotes] = useState("");
  const [saving, setSaving] = useState(false);

  const { data: locations } = useQuery(warehouseLocationListOptions());

  const createMutation = useApiMutation<
    {
      notes: string | null;
      items: {
        item_id: number;
        location_id: number | null;
        actual_qty: number;
      }[];
    },
    { id?: number }
  >({
    url: () => "/api/admin/warehouse/inventory-sessions",
    method: () => "POST",
    invalidate: ["warehouse"],
    onSuccess: (data) => {
      alert.success("Inventura byla vytvořena");
      navigate(`/warehouse/inventory/${data?.id}`);
    },
  });

  // All hooks above this line — permission gate is the last thing before render.
  if (!hasPermission("warehouse.inventory")) return <Forbidden />;

  const validate = (): boolean => {
    const validItems = items.filter((l) => l.item_id !== null);
    if (validItems.length === 0) {
      alert.error("Přidejte alespoň jednu položku");
      return false;
    }
    for (const l of validItems) {
      if (!Number.isFinite(l.actual_qty) || l.actual_qty < 0) {
        alert.error("Skutečné množství musí být platné číslo");
        return false;
      }
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!validate()) return;
    setSaving(true);
    try {
      await createMutation.mutateAsync({
        notes: notes.trim() || null,
        items: items
          .filter((l) => l.item_id !== null)
          .map((l) => ({
            item_id: l.item_id!,
            location_id: l.location_id,
            actual_qty: l.actual_qty,
          })),
      });
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

  const addItem = () => {
    setItems((prev) => [
      ...prev,
      { key: nextKey(), item_id: null, location_id: null, actual_qty: 0 },
    ]);
  };

  const removeItem = (index: number) => {
    setItems((prev) => prev.filter((_, i) => i !== index));
  };

  const updateItem = (
    index: number,
    field: keyof InventoryItem,
    value: unknown,
  ) => {
    setItems((prev) => {
      const updated = [...prev];
      updated[index] = { ...updated[index], [field]: value };
      return updated;
    });
  };

  const locationOptions = [
    { value: "", label: "-- bez lokace --" },
    ...(locations ?? []).map((loc: WarehouseLocation) => ({
      value: String(loc.id),
      label: `${loc.code} - ${loc.name}`,
    })),
  ];

  return (
    <PageEnter>
      {/* Header */}
      <Box
        sx={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 2,
          mb: 3,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
          <IconButton
            component={RouterLink}
            to="/warehouse/inventory"
            title="Zpět na seznam"
            aria-label="Zpět na seznam"
          >
            {BackIcon}
          </IconButton>
          <Typography variant="h4">Nová inventura</Typography>
        </Box>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <Button onClick={handleSubmit} disabled={saving}>
            {saving ? "Ukládání..." : "Vytvořit inventuru"}
          </Button>
        </Box>
      </Box>

      {/* Notes */}
      <Card sx={{ mb: 3 }}>
        <Typography variant="subtitle2" sx={{ mb: 2, fontWeight: 600 }}>
          Základní údaje
        </Typography>
        <Field label="Poznámky">
          <TextField
            multiline
            minRows={3}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Volitelné poznámky k inventuře"
          />
        </Field>
      </Card>

      {/* Lines */}
      <Card sx={{ mb: 3 }}>
        <Typography variant="subtitle2" sx={{ mb: 2, fontWeight: 600 }}>
          Položky
        </Typography>
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
          {items.map((item, index) => (
            <Box
              key={item.key}
              sx={{
                display: "grid",
                gridTemplateColumns: {
                  xs: "1fr",
                  md: "minmax(180px, 2fr) minmax(140px, 1.5fr) 120px auto",
                },
                gap: 1,
                alignItems: "start",
              }}
            >
              <ItemPicker
                value={item.item_id}
                onChange={(id) => updateItem(index, "item_id", id)}
              />
              <Select
                value={
                  item.location_id === null ? "" : String(item.location_id)
                }
                onChange={(val) =>
                  updateItem(index, "location_id", val ? Number(val) : null)
                }
                options={locationOptions}
              />
              <TextField
                type="number"
                value={item.actual_qty || ""}
                onChange={(e) =>
                  updateItem(index, "actual_qty", parseDecimal(e.target.value))
                }
                inputProps={{
                  min: 0,
                  step: 0.001,
                  inputMode: "decimal",
                  pattern: "[0-9]+([\\.,][0-9]+)?",
                  "aria-label": `Skutečné množství, řádek ${index + 1}`,
                }}
                placeholder="Skutečné množství"
              />
              <IconButton
                color="error"
                onClick={() => removeItem(index)}
                title="Odebrat řádek"
                aria-label="Odebrat řádek"
                sx={{ justifySelf: { xs: "start", md: "center" } }}
              >
                {RemoveIcon}
              </IconButton>
            </Box>
          ))}
        </Box>
        <Button
          variant="outlined"
          color="inherit"
          startIcon={PlusIcon}
          onClick={addItem}
          sx={{ mt: 2 }}
        >
          Přidat položku
        </Button>
      </Card>
    </PageEnter>
  );
}
