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

import { formatCurrency, formatDate } from "../utils/formatters";
import {
  warehouseReceiptDetailOptions,
  type WarehouseReceipt,
} from "../lib/queries/warehouse";
import { useApiMutation } from "../lib/queries/mutations";

const STATUS_BADGE: Record<string, string> = {
  DRAFT: "admin-badge-warning",
  CONFIRMED: "admin-badge-active",
  CANCELLED: "admin-badge-danger",
};

const STATUS_LABEL: Record<string, string> = {
  DRAFT: "Návrh",
  CONFIRMED: "Potvrzeno",
  CANCELLED: "Zrušeno",
};

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

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

  const [cancelConfirm, setCancelConfirm] = useState(false);

  const {
    data: receipt,
    isPending,
    error,
  } = useQuery(warehouseReceiptDetailOptions(id));

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

  const canOperate = hasPermission("warehouse.operate");

  const confirmMutation = useApiMutation<void, void>({
    url: () =>
      receipt
        ? `/api/admin/warehouse/receipts/${receipt.id}/confirm`
        : "/api/admin/warehouse/receipts/0/confirm",
    method: () => "POST",
    invalidate: ["warehouse"],
    onSuccess: () => {
      alert.success("Doklad byl potvrzen");
    },
  });

  const cancelMutation = useApiMutation<void, void>({
    url: () =>
      receipt
        ? `/api/admin/warehouse/receipts/${receipt.id}/cancel`
        : "/api/admin/warehouse/receipts/0/cancel",
    method: () => "POST",
    invalidate: ["warehouse"],
    onSuccess: () => {
      setCancelConfirm(false);
      alert.success("Doklad byl zrušen");
    },
  });

  const deleteAttachmentMutation = useApiMutation<
    { attachmentId: number },
    void
  >({
    url: ({ attachmentId }) =>
      receipt
        ? `/api/admin/warehouse/receipts/${receipt.id}/attachments/${attachmentId}`
        : `/api/admin/warehouse/receipts/0/attachments/0`,
    method: () => "DELETE",
    invalidate: ["warehouse"],
    onSuccess: () => {
      alert.success("Příloha byla smazána");
    },
  });

  const handleConfirm = async () => {
    if (!receipt) return;
    try {
      await confirmMutation.mutateAsync(undefined);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleCancel = async () => {
    if (!receipt) return;
    try {
      await cancelMutation.mutateAsync(undefined);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleDeleteAttachment = async (attachmentId: number) => {
    if (!receipt) return;
    try {
      await deleteAttachmentMutation.mutateAsync({ attachmentId });
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const confirming = confirmMutation.isPending;
  const cancelling = cancelMutation.isPending;

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

  if (error || !receipt) {
    return (
      <div>
        <div className="admin-page-header">
          <div>
            <Link
              to="/warehouse/receipts"
              className="admin-btn-icon"
              title="Zpět na seznam"
            >
              <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>
            </Link>
          </div>
        </div>
        <div className="admin-card">
          <div className="admin-card-body">
            <div className="admin-empty-state">
              <p>Doklad nebyl nalezen.</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const r = receipt as WarehouseReceipt;
  const items = r.items ?? [];
  const attachments = r.attachments ?? [];

  return (
    <div>
      {/* Header */}
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
          <Link
            to="/warehouse/receipts"
            className="admin-btn-icon"
            title="Zpět na seznam"
            aria-label="Zpět na seznam"
          >
            <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>
          </Link>
          <div>
            <h1 className="admin-page-title">
              {r.receipt_number || "Nový doklad"}
            </h1>
            {r.supplier?.name && (
              <p className="admin-page-subtitle">{r.supplier.name}</p>
            )}
          </div>
          <span
            className={`admin-badge ${STATUS_BADGE[r.status] ?? ""}`}
            style={{ marginLeft: "0.5rem" }}
          >
            {STATUS_LABEL[r.status] ?? r.status}
          </span>
        </div>
        {canOperate && (
          <div className="admin-page-actions">
            {r.status === "DRAFT" && (
              <>
                <button
                  onClick={() => navigate(`/warehouse/receipts/${r.id}/edit`)}
                  className="admin-btn admin-btn-secondary"
                >
                  Upravit
                </button>
                <button
                  onClick={handleConfirm}
                  className="admin-btn admin-btn-primary"
                  disabled={confirming}
                >
                  {confirming ? "Potvrzování..." : "Potvrdit"}
                </button>
                <button
                  onClick={() => setCancelConfirm(true)}
                  className="admin-btn admin-btn-secondary"
                  style={{ color: "var(--danger)" }}
                >
                  Zrušit
                </button>
              </>
            )}
            {r.status === "CONFIRMED" && (
              <button
                onClick={() => setCancelConfirm(true)}
                className="admin-btn admin-btn-secondary"
                style={{ color: "var(--danger)" }}
              >
                Zrušit
              </button>
            )}
          </div>
        )}
      </motion.div>

      {/* Header info */}
      <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">
          <h3 className="admin-card-title">Základní údaje</h3>
          <div className="admin-form">
            <div className="admin-form-row">
              <FormField label="Číslo dokladu">
                <div className="admin-mono fw-500">
                  {r.receipt_number || "—"}
                </div>
              </FormField>
              <FormField label="Dodavatel">
                <div className="admin-mono fw-500">
                  {r.supplier?.name || "—"}
                </div>
              </FormField>
            </div>
            <div className="admin-form-row">
              <FormField label="Číslo dodacího listu">
                <div className="admin-mono">
                  {r.delivery_note_number || "—"}
                </div>
              </FormField>
              <FormField label="Datum dodacího listu">
                <div className="admin-mono">
                  {formatDate(r.delivery_note_date)}
                </div>
              </FormField>
            </div>
            <div className="admin-form-row">
              <FormField label="Přijal">
                <div className="admin-mono fw-500">
                  {r.received_by_user
                    ? `${r.received_by_user.first_name} ${r.received_by_user.last_name}`
                    : "—"}
                </div>
              </FormField>
              <FormField label="Vytvořeno">
                <div className="admin-mono">{formatDate(r.created_at)}</div>
              </FormField>
            </div>
            {r.notes && (
              <FormField label="Poznámky">
                <div style={{ whiteSpace: "pre-wrap" }}>{r.notes}</div>
              </FormField>
            )}
          </div>
        </div>
      </motion.div>

      {/* Lines table */}
      <motion.div
        className="admin-card"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.08 }}
      >
        <div className="admin-card-body">
          <h3 className="admin-card-title">Položky</h3>
          {items.length === 0 ? (
            <div className="admin-empty-state">Žádné řádky</div>
          ) : (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Položka</th>
                    <th>Množství</th>
                    <th>Cena/ks</th>
                    <th>Celkem</th>
                    <th>Lokace</th>
                    <th>Poznámka</th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((item) => (
                    <tr key={item.id}>
                      <td className="fw-500">
                        {item.item?.name || `ID: ${item.item_id}`}
                      </td>
                      <td className="admin-mono">{Number(item.quantity)}</td>
                      <td className="admin-mono">
                        {formatCurrency(Number(item.unit_price), "CZK")}
                      </td>
                      <td className="admin-mono fw-500">
                        {formatCurrency(
                          Number(item.quantity) * Number(item.unit_price),
                          "CZK",
                        )}
                      </td>
                      <td className="admin-mono">
                        {item.location?.code || "—"}
                      </td>
                      <td>{item.notes || "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </motion.div>

      {/* Attachments */}
      <motion.div
        className="admin-card"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.1 }}
      >
        <div className="admin-card-body">
          <h3 className="admin-card-title">Přílohy</h3>
          {attachments.length === 0 ? (
            <div className="admin-empty-state">Žádné přílohy</div>
          ) : (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Název souboru</th>
                    <th>Velikost</th>
                    <th>Datum</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {attachments.map((att) => (
                    <tr key={att.id}>
                      <td className="fw-500">
                        <a
                          href={`/api/admin/warehouse/receipts/${r.id}/attachments/${att.id}`}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          {att.file_name}
                        </a>
                      </td>
                      <td className="admin-mono">
                        {formatFileSize(att.file_size)}
                      </td>
                      <td className="admin-mono">
                        {formatDate(att.created_at)}
                      </td>
                      <td>
                        <div className="admin-table-actions">
                          {r.status === "DRAFT" && canOperate && (
                            <button
                              onClick={() => handleDeleteAttachment(att.id)}
                              className="admin-btn-icon danger"
                              title="Smazat přílohu"
                              aria-label="Smazat přílohu"
                            >
                              <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>

      {/* Cancel confirmation modal */}
      <ConfirmModal
        isOpen={cancelConfirm}
        onClose={() => setCancelConfirm(false)}
        onConfirm={handleCancel}
        title="Zrušit doklad"
        message={`Opravdu chcete zrušit příjmový doklad „${r.receipt_number || r.id}"?`}
        confirmText="Zrušit doklad"
        confirmVariant="danger"
        loading={cancelling}
      />
    </div>
  );
}
