import { useState } from "react";
import { useNavigate, Link as RouterLink } from "react-router-dom";
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 { formatCurrency, formatDate } from "../utils/formatters";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { useApiMutation } from "../lib/queries/mutations";
import apiFetch from "../utils/api";
import {
  issuedOrderListOptions,
  type IssuedOrder,
} from "../lib/queries/issued-orders";
import {
  Card,
  DataTable,
  Pagination,
  ConfirmDialog,
  TextField,
  Select,
  StatusChip,
  FilterBar,
  EmptyState,
  LoadingState,
  type DataColumn,
} from "../ui";
import {
  ISSUED_ORDER_STATUS,
  statusLabel,
  statusColor,
  statusOptions,
} from "../lib/documentStatus";

const API_BASE = "/api/admin";

const STATUS_OPTIONS = statusOptions(ISSUED_ORDER_STATUS, {
  value: "",
  label: "Všechny stavy",
});

const ViewIcon = (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
    <circle cx="12" cy="12" r="3" />
  </svg>
);
const PdfIcon = (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
    <polyline points="14 2 14 8 20 8" />
    <line x1="16" y1="13" x2="8" y2="13" />
    <line x1="16" y1="17" x2="8" y2="17" />
  </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>
);

interface IssuedOrdersProps {
  month: number;
  year: number;
}

export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const navigate = useNavigate();

  const { sort, order, handleSort } = useTableSort("po_number");
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 300);
  const [status, setStatus] = useState("");
  const [page, setPage] = useState(1);

  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    order: IssuedOrder | null;
  }>({ show: false, order: null });

  const deleteMutation = useApiMutation<
    { id: number },
    { message?: string; error?: string }
  >({
    url: ({ id }) => `${API_BASE}/issued-orders/${id}`,
    method: () => "DELETE",
    invalidate: ["issued-orders"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, order: null });
      alert.success(data?.message || "Objednávka byla smazána");
    },
  });

  const {
    items: orders,
    pagination,
    isPending,
    isFetching,
  } = usePaginatedQuery<IssuedOrder>(
    issuedOrderListOptions({
      search: debouncedSearch,
      sort,
      order,
      page,
      perPage: 20,
      status: status || undefined,
      month,
      year,
    }),
  );

  if (!hasPermission("orders.view")) return <Forbidden />;

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

  const handleExportPdf = async (o: IssuedOrder) => {
    // Authenticated open: apiFetch attaches the access token, then we hand the
    // resulting PDF blob to a window. A raw window.open(url) would be an
    // unauthenticated top-level navigation and 401 on the token-guarded route.
    const newWindow = window.open("", "_blank");
    try {
      const response = await apiFetch(
        `${API_BASE}/issued-orders-pdf/${o.id}?lang=cs`,
      );
      if (!response.ok) {
        newWindow?.close();
        alert.error("Nepodařilo se vygenerovat PDF");
        return;
      }
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      if (newWindow) newWindow.location.href = url;
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    } catch {
      newWindow?.close();
      alert.error("Chyba při generování PDF");
    }
  };

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

  const columns: DataColumn<IssuedOrder>[] = [
    {
      key: "po_number",
      header: "Číslo",
      width: "16%",
      sortKey: "po_number",
      mono: true,
      render: (o) => (
        <Box
          component={RouterLink}
          to={`/orders/issued/${o.id}`}
          sx={{
            color: "primary.main",
            textDecoration: "none",
            "&:hover": { textDecoration: "underline" },
          }}
        >
          {o.po_number || "—"}
        </Box>
      ),
    },
    {
      key: "customer_name",
      header: "Dodavatel",
      width: "24%",
      render: (o) => o.customer_name || "—",
    },
    {
      key: "status",
      header: "Stav",
      width: "14%",
      sortKey: "status",
      render: (o) => (
        <StatusChip
          label={statusLabel(ISSUED_ORDER_STATUS, o.status)}
          color={statusColor(ISSUED_ORDER_STATUS, o.status)}
        />
      ),
    },
    {
      key: "order_date",
      header: "Datum",
      width: "13%",
      sortKey: "order_date",
      mono: true,
      render: (o) => (o.order_date ? formatDate(o.order_date) : "—"),
    },
    {
      key: "total",
      header: "Celkem",
      width: "14%",
      align: "right",
      mono: true,
      bold: true,
      render: (o) => formatCurrency(o.total, o.currency ?? "CZK"),
    },
    {
      key: "actions",
      header: "Akce",
      width: "14%",
      align: "right",
      render: (o) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => navigate(`/orders/issued/${o.id}`)}
            aria-label={hasPermission("orders.edit") ? "Upravit" : "Detail"}
            title={hasPermission("orders.edit") ? "Upravit" : "Detail"}
          >
            {ViewIcon}
          </IconButton>
          {hasPermission("orders.export") && (
            <IconButton
              size="small"
              onClick={() => handleExportPdf(o)}
              aria-label="PDF"
              title="PDF"
            >
              {PdfIcon}
            </IconButton>
          )}
          {hasPermission("orders.delete") && (
            <IconButton
              size="small"
              color="error"
              onClick={() => setDeleteConfirm({ show: true, order: o })}
              aria-label="Smazat"
              title="Smazat"
            >
              {DeleteIcon}
            </IconButton>
          )}
        </Box>
      ),
    },
  ];

  return (
    <>
      <FilterBar>
        <Box sx={{ flex: "1 1 320px" }}>
          <TextField
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            placeholder="Hledat podle čísla nebo dodavatele..."
            fullWidth
          />
        </Box>
        <Box sx={{ flex: "0 1 200px" }}>
          <Select
            value={status}
            onChange={(value) => {
              setStatus(value);
              setPage(1);
            }}
            options={STATUS_OPTIONS}
          />
        </Box>
      </FilterBar>

      <Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
        <DataTable<IssuedOrder>
          columns={columns}
          rows={orders}
          rowKey={(o) => o.id}
          sortBy={sort}
          sortDir={order}
          onSort={handleSort}
          empty={
            <EmptyState
              title="Zatím žádné vydané objednávky."
              description={
                hasPermission("orders.create")
                  ? "Vytvořte první tlačítkem „Vytvořit objednávku vydanou“."
                  : undefined
              }
            />
          }
        />
        <Pagination
          page={page}
          pageCount={pagination?.total_pages ?? 1}
          onChange={setPage}
        />
      </Card>

      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, order: null })}
        onConfirm={handleDelete}
        title="Smazat objednávku"
        message={
          deleteConfirm.order
            ? `Opravdu chcete smazat objednávku „${deleteConfirm.order.po_number || ""}"? Tato akce je nevratná.`
            : ""
        }
        confirmText="Smazat"
        cancelText="Zrušit"
        confirmVariant="danger"
        loading={deleteMutation.isPending}
      />
    </>
  );
}
