import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import { Link, useNavigate } from "react-router-dom";
import apiFetch from "../utils/api";
import Forbidden from "../components/Forbidden";
import { motion } from "framer-motion";
import ConfirmModal from "../components/ConfirmModal";
import FormModal from "../components/FormModal";
import FormField from "../components/FormField";

import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
import SortIcon from "../components/SortIcon";
import useTableSort from "../hooks/useTableSort";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
  orderListOptions,
  orderNextNumberOptions,
} from "../lib/queries/orders";
import { offerCustomersOptions } from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import Pagination from "../components/Pagination";

const API_BASE = "/api/admin";

const STATUS_LABELS: Record<string, string> = {
  prijata: "Přijatá",
  v_realizaci: "V realizaci",
  dokoncena: "Dokončená",
  stornovana: "Stornována",
};

const STATUS_CLASSES: Record<string, string> = {
  prijata: "admin-badge-order-prijata",
  v_realizaci: "admin-badge-order-realizace",
  dokoncena: "admin-badge-order-dokoncena",
  stornovana: "admin-badge-order-stornovana",
};

interface Order {
  id: number;
  order_number: string;
  quotation_id: number;
  quotation_number: string;
  customer_name: string;
  status: string;
  created_at: string;
  total: number;
  currency: string;
  invoice_id?: number;
}

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

  const { sort, order, handleSort, activeSort } = useTableSort("order_number");
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);

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

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

  const [showCreate, setShowCreate] = useState(false);
  const [createForm, setCreateForm] = useState({
    customer_id: "",
    customer_order_number: "",
    currency: "CZK",
    vat_rate: "21",
    apply_vat: true,
    scope_title: "",
    scope_description: "",
    notes: "",
    create_project: true,
    price: "",
    quantity: "1",
  });
  const [creating, setCreating] = useState(false);
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [orderAttachment, setOrderAttachment] = useState<File | null>(null);

  const customersQuery = useQuery({
    ...offerCustomersOptions(),
    enabled: showCreate,
  });
  const nextNumberQuery = useQuery({
    ...orderNextNumberOptions(),
    enabled: showCreate,
  });

  const openCreate = () => {
    setCreateForm({
      customer_id: "",
      customer_order_number: "",
      currency: "CZK",
      vat_rate: "21",
      apply_vat: true,
      scope_title: "",
      scope_description: "",
      notes: "",
      create_project: true,
      price: "",
      quantity: "1",
    });
    setOrderAttachment(null);
    setShowCreate(true);
  };

  const handleCreate = async () => {
    setCreating(true);
    try {
      const priceNum = createForm.price ? Number(createForm.price) : 0;
      const qtyNum = createForm.quantity ? Number(createForm.quantity) : 1;
      const items =
        priceNum > 0
          ? [
              {
                description: createForm.scope_title || "Položka",
                quantity: qtyNum,
                unit_price: priceNum,
                is_included_in_total: true,
              },
            ]
          : undefined;

      let fetchOptions: RequestInit;
      if (orderAttachment) {
        const fd = new FormData();
        if (createForm.customer_id)
          fd.append("customer_id", createForm.customer_id);
        fd.append("customer_order_number", createForm.customer_order_number);
        fd.append("currency", createForm.currency);
        fd.append("vat_rate", createForm.vat_rate);
        fd.append("apply_vat", createForm.apply_vat ? "1" : "0");
        fd.append("scope_title", createForm.scope_title);
        fd.append("scope_description", createForm.scope_description);
        fd.append("notes", createForm.notes);
        fd.append("create_project", createForm.create_project ? "1" : "0");
        if (items) fd.append("items", JSON.stringify(items));
        fd.append("attachment", orderAttachment);
        fetchOptions = { method: "POST", body: fd };
      } else {
        fetchOptions = {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            customer_id: createForm.customer_id
              ? Number(createForm.customer_id)
              : null,
            customer_order_number: createForm.customer_order_number,
            currency: createForm.currency,
            vat_rate: createForm.vat_rate,
            apply_vat: createForm.apply_vat,
            scope_title: createForm.scope_title,
            scope_description: createForm.scope_description,
            notes: createForm.notes,
            create_project: createForm.create_project,
            ...(items ? { items } : {}),
          }),
        };
      }

      const response = await apiFetch(`${API_BASE}/orders`, fetchOptions);
      const result = await response.json();
      if (result.success) {
        setShowCreate(false);
        alert.success(result.message || "Objednávka byla vytvořena");
        await queryClient.invalidateQueries({ queryKey: ["orders"] });
        await queryClient.invalidateQueries({ queryKey: ["projects"] });
        await queryClient.invalidateQueries({ queryKey: ["offers"] });
        await queryClient.invalidateQueries({ queryKey: ["invoices"] });
        if (result.data?.id) navigate(`/orders/${result.data.id}`);
      } else {
        alert.error(result.error || "Nepodařilo se vytvořit objednávku");
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setCreating(false);
    }
  };

  const {
    items: orders,
    pagination,
    isPending,
    isFetching,
  } = usePaginatedQuery<Order>(orderListOptions({ search, sort, order, page }));

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

  const handleDelete = async () => {
    if (!deleteConfirm.order) return;
    try {
      await deleteMutation.mutateAsync({
        id: deleteConfirm.order.id,
        delete_files: deleteFiles,
      });
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "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">Objednávky</h1>
          <p className="admin-page-subtitle">
            {pagination?.total ?? orders.length}{" "}
            {czechPlural(
              pagination?.total ?? orders.length,
              "objednávka",
              "objednávky",
              "objednávek",
            )}
          </p>
        </div>
        {hasPermission("orders.create") && (
          <div className="admin-page-actions">
            <button
              onClick={openCreate}
              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>
              Vytvořit objednávku
            </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 }}
        style={{ opacity: isFetching ? 0.6 : 1, transition: "opacity 0.2s" }}
      >
        <div className="admin-card-body">
          <div className="admin-search-bar mb-4">
            <input
              type="text"
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
              className="admin-form-input"
              placeholder="Hledat podle čísla, nabídky, projektu nebo zákazníka..."
            />
          </div>

          {orders.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="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z" />
                  <line x1="3" y1="6" x2="21" y2="6" />
                  <path d="M16 10a4 4 0 0 1-8 0" />
                </svg>
              </div>
              <p>Zatím nejsou žádné objednávky.</p>
              <p className="text-tertiary" style={{ fontSize: "0.875rem" }}>
                Objednávky se vytvářejí z nabídek.
              </p>
            </div>
          ) : (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th
                      style={{ cursor: "pointer" }}
                      onClick={() => handleSort("order_number")}
                    >
                      Číslo{" "}
                      <SortIcon
                        column="order_number"
                        sort={activeSort}
                        order={order}
                      />
                    </th>
                    <th>Nabídka</th>
                    <th>Zákazník</th>
                    <th
                      style={{ cursor: "pointer" }}
                      onClick={() => handleSort("status")}
                    >
                      Stav{" "}
                      <SortIcon
                        column="status"
                        sort={activeSort}
                        order={order}
                      />
                    </th>
                    <th
                      style={{ cursor: "pointer" }}
                      onClick={() => handleSort("created_at")}
                    >
                      Datum{" "}
                      <SortIcon
                        column="created_at"
                        sort={activeSort}
                        order={order}
                      />
                    </th>
                    <th className="text-right">Celkem</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {(orders as Order[]).map((o) => (
                    <tr key={o.id}>
                      <td className="admin-mono">
                        <Link to={`/orders/${o.id}`} className="link-accent">
                          {o.order_number}
                        </Link>
                      </td>
                      <td>
                        <Link
                          to={`/offers/${o.quotation_id}`}
                          className="text-secondary"
                          style={{ textDecoration: "none" }}
                        >
                          {o.quotation_number}
                        </Link>
                      </td>
                      <td>{o.customer_name || "—"}</td>
                      <td>
                        <span
                          className={`admin-badge ${STATUS_CLASSES[o.status] || ""}`}
                        >
                          {STATUS_LABELS[o.status] || o.status}
                        </span>
                      </td>
                      <td className="admin-mono">{formatDate(o.created_at)}</td>
                      <td className="admin-mono text-right fw-500">
                        {formatCurrency(o.total, o.currency)}
                      </td>
                      <td>
                        <div className="admin-table-actions">
                          <Link
                            to={`/orders/${o.id}`}
                            className="admin-btn-icon"
                            title="Detail"
                            aria-label="Detail"
                          >
                            <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>
                          </Link>
                          {o.invoice_id ? (
                            <Link
                              to={`/invoices/${o.invoice_id}`}
                              className="admin-btn-icon accent"
                              title="Zobrazit fakturu"
                              aria-label="Zobrazit fakturu"
                            >
                              <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" />
                                <text
                                  x="12"
                                  y="16.5"
                                  textAnchor="middle"
                                  fill="currentColor"
                                  stroke="none"
                                  fontSize="9"
                                  fontWeight="700"
                                >
                                  F
                                </text>
                              </svg>
                            </Link>
                          ) : (
                            hasPermission("invoices.create") && (
                              <Link
                                to={`/invoices/new?fromOrder=${o.id}`}
                                className="admin-btn-icon"
                                title="Vytvořit fakturu"
                                aria-label="Vytvořit fakturu"
                              >
                                <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="12" y1="11" x2="12" y2="17" />
                                  <line x1="9" y1="14" x2="15" y2="14" />
                                </svg>
                              </Link>
                            )
                          )}
                          {hasPermission("orders.delete") && (
                            <button
                              onClick={() =>
                                setDeleteConfirm({ show: true, order: o })
                              }
                              className="admin-btn-icon danger"
                              title="Smazat"
                            >
                              <svg
                                width="18"
                                height="18"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                              >
                                <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>
          )}
          <Pagination pagination={pagination} onPageChange={setPage} />
        </div>
      </motion.div>

      <ConfirmModal
        isOpen={deleteConfirm.show}
        onClose={() => {
          setDeleteConfirm({ show: false, order: null });
          setDeleteFiles(false);
        }}
        onConfirm={handleDelete}
        title="Smazat objednávku"
        message={
          <>
            Opravdu chcete smazat objednávku &quot;
            {deleteConfirm.order?.order_number}&quot;? Bude smazán i přidružený
            projekt. Tato akce je nevratná.
            <label
              className="admin-form-checkbox"
              style={{ marginTop: "1rem", display: "flex" }}
            >
              <input
                type="checkbox"
                checked={deleteFiles}
                onChange={(e) => setDeleteFiles(e.target.checked)}
              />
              <span>Smazat i soubory projektu na disku</span>
            </label>
          </>
        }
        confirmText="Smazat"
        cancelText="Zrušit"
        type="danger"
        loading={deleteMutation.isPending}
      />

      <FormModal
        isOpen={showCreate}
        onClose={() => setShowCreate(false)}
        onSubmit={handleCreate}
        title="Vytvořit objednávku bez nabídky"
        submitLabel="Vytvořit"
        loading={creating}
      >
        <div className="admin-form">
          <div className="admin-form-row">
            <FormField label="Zákazník">
              <select
                value={createForm.customer_id}
                onChange={(e) =>
                  setCreateForm({ ...createForm, customer_id: e.target.value })
                }
                className="admin-form-input"
              >
                <option value="">— bez zákazníka —</option>
                {(customersQuery.data ?? []).map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
            </FormField>
            <FormField label="Číslo objednávky zákazníka">
              <input
                type="text"
                value={createForm.customer_order_number}
                onChange={(e) =>
                  setCreateForm({
                    ...createForm,
                    customer_order_number: e.target.value,
                  })
                }
                className="admin-form-input"
              />
            </FormField>
          </div>

          <div className="admin-form-row">
            <FormField label="Měna">
              <select
                value={createForm.currency}
                onChange={(e) =>
                  setCreateForm({ ...createForm, currency: e.target.value })
                }
                className="admin-form-input"
              >
                <option value="CZK">CZK</option>
                <option value="EUR">EUR</option>
                <option value="USD">USD</option>
                <option value="GBP">GBP</option>
              </select>
            </FormField>
            <FormField label="Sazba DPH (%)">
              <input
                type="number"
                inputMode="numeric"
                value={createForm.vat_rate}
                onChange={(e) =>
                  setCreateForm({ ...createForm, vat_rate: e.target.value })
                }
                className="admin-form-input"
                min="0"
              />
            </FormField>
          </div>

          <div className="admin-form-row">
            <FormField label="Cena za jednotku (bez DPH)">
              <input
                type="number"
                inputMode="decimal"
                value={createForm.price}
                onChange={(e) =>
                  setCreateForm({ ...createForm, price: e.target.value })
                }
                className="admin-form-input"
                min="0"
                step="0.01"
                placeholder="0"
              />
            </FormField>
            <FormField label="Množství">
              <input
                type="number"
                inputMode="decimal"
                value={createForm.quantity}
                onChange={(e) =>
                  setCreateForm({ ...createForm, quantity: e.target.value })
                }
                className="admin-form-input"
                min="0"
                step="1"
              />
            </FormField>
          </div>

          <FormField label="Předmět (scope)">
            <input
              type="text"
              value={createForm.scope_title}
              onChange={(e) =>
                setCreateForm({ ...createForm, scope_title: e.target.value })
              }
              className="admin-form-input"
            />
          </FormField>

          <FormField label="Popis">
            <textarea
              value={createForm.scope_description}
              onChange={(e) =>
                setCreateForm({
                  ...createForm,
                  scope_description: e.target.value,
                })
              }
              className="admin-form-input"
              rows={3}
            />
          </FormField>

          <FormField label="Poznámka">
            <textarea
              value={createForm.notes}
              onChange={(e) =>
                setCreateForm({ ...createForm, notes: e.target.value })
              }
              className="admin-form-input"
              rows={2}
            />
          </FormField>

          <FormField label="Příloha (PO zákazníka, PDF)">
            {orderAttachment ? (
              <div className="flex-row gap-2">
                <span className="text-md">
                  {orderAttachment.name}{" "}
                  <span className="text-tertiary">
                    ({(orderAttachment.size / 1024).toFixed(0)} KB)
                  </span>
                </span>
                <button
                  type="button"
                  onClick={() => setOrderAttachment(null)}
                  className="admin-btn-icon"
                  title="Odebrat"
                  style={{ marginLeft: "auto" }}
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <path d="M18 6L6 18M6 6l12 12" />
                  </svg>
                </button>
              </div>
            ) : (
              <label
                className="admin-btn admin-btn-secondary admin-btn-sm"
                style={{
                  cursor: "pointer",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "0.4rem",
                }}
              >
                Vybrat soubor
                <input
                  type="file"
                  accept="application/pdf"
                  onChange={(e) =>
                    setOrderAttachment(e.target.files?.[0] || null)
                  }
                  style={{ display: "none" }}
                />
              </label>
            )}
          </FormField>

          <label className="admin-form-checkbox">
            <input
              type="checkbox"
              checked={createForm.apply_vat}
              onChange={(e) =>
                setCreateForm({ ...createForm, apply_vat: e.target.checked })
              }
            />
            <span>Účtovat DPH</span>
          </label>

          <label className="admin-form-checkbox">
            <input
              type="checkbox"
              checked={createForm.create_project}
              onChange={(e) =>
                setCreateForm({
                  ...createForm,
                  create_project: e.target.checked,
                })
              }
            />
            <span>Vytvořit propojený projekt</span>
          </label>

          <p className="admin-form-hint">
            Číslo objednávky:{" "}
            <strong>
              {nextNumberQuery.data?.number ??
                nextNumberQuery.data?.next_number ??
                "…"}
            </strong>{" "}
            (přiděleno automaticky)
          </p>
        </div>
      </FormModal>
    </div>
  );
}
