import { useState, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link as RouterLink } from "react-router-dom";
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 {
  tripListOptions,
  tripVehiclesOptions,
  tripUsersOptions,
  type BackendTrip,
} from "../lib/queries/trips";
import { companySettingsOptions } from "../lib/queries/settings";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import { useApiMutation } from "../lib/queries/mutations";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  Select,
  DateField,
  MonthField,
  StatusChip,
  FilterBar,
  LoadingState,
  EmptyState,
  StatCard,
  PageEnter,
  type DataColumn,
} from "../ui";

const API_BASE = "/api/admin";

interface Trip {
  id: number;
  vehicle_id: number | string;
  trip_date: string;
  start_km: number;
  end_km: number;
  distance: number;
  route_from: string;
  route_to: string;
  is_business: number | boolean;
  notes?: string;
  spz: string;
  driver_name: string;
}

interface EditForm {
  vehicle_id: string;
  trip_date: string;
  start_km: string | number;
  end_km: string | number;
  route_from: string;
  route_to: string;
  is_business: number;
  notes: string;
}

function mapTrip(bt: BackendTrip): Trip {
  const distance = bt.distance ?? bt.end_km - bt.start_km;
  return {
    id: bt.id,
    vehicle_id: bt.vehicle_id,
    trip_date: bt.trip_date,
    start_km: bt.start_km,
    end_km: bt.end_km,
    distance,
    route_from: bt.route_from,
    route_to: bt.route_to,
    is_business: bt.is_business ? 1 : 0,
    notes: bt.notes || undefined,
    spz: bt.vehicles?.spz ?? "",
    driver_name: bt.users ? `${bt.users.first_name} ${bt.users.last_name}` : "",
  };
}

const PrintIcon = (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <polyline points="6 9 6 2 18 2 18 9" />
    <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" />
    <rect x="6" y="14" width="12" height="8" />
  </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>
);

const TripsIcon = (
  <svg
    width="22"
    height="22"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <line x1="12" y1="20" x2="12" y2="10" />
    <line x1="18" y1="20" x2="18" y2="4" />
    <line x1="6" y1="20" x2="6" y2="16" />
  </svg>
);
const TotalIcon = (
  <svg
    width="22"
    height="22"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
  </svg>
);
const BusinessIcon = (
  <svg
    width="22"
    height="22"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <rect x="1" y="3" width="15" height="13" rx="2" ry="2" />
    <path d="M16 8h2a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-1" />
    <circle cx="5.5" cy="18" r="2" />
    <circle cx="18.5" cy="18" r="2" />
    <path d="M8 18h8" />
  </svg>
);

export default function TripsAdmin() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const [filterPeriod, setFilterPeriod] = useState(() => {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
  });
  const [filterVehicleId, setFilterVehicleId] = useState("");
  const [filterUserId, setFilterUserId] = useState("");
  const printRef = useRef<HTMLDivElement>(null);

  const [showEditModal, setShowEditModal] = useState(false);
  const [editingTrip, setEditingTrip] = useState<Trip | null>(null);
  const [editForm, setEditForm] = useState<EditForm>({
    vehicle_id: "",
    trip_date: "",
    start_km: "",
    end_km: "",
    route_from: "",
    route_to: "",
    is_business: 1,
    notes: "",
  });

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

  const { data: vehiclesData = [] } = useQuery(tripVehiclesOptions());
  const vehicles = vehiclesData;

  const { data: tripUsersData = [] } = useQuery(tripUsersOptions());
  const tripUsers = tripUsersData;

  const { data: companySettings } = useQuery(companySettingsOptions());
  const companyName = companySettings?.company_name ?? "";

  const { data: tripsData, isPending } = useQuery(
    tripListOptions({
      month: Number(filterPeriod.slice(5, 7)) || undefined,
      year: Number(filterPeriod.slice(0, 4)) || undefined,
      vehicleId: filterVehicleId ? Number(filterVehicleId) : undefined,
      userId: filterUserId ? Number(filterUserId) : undefined,
      perPage: 100,
    }),
  );
  const trips = (tripsData ?? []).map(mapTrip);

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

  // useApiMutation JSON.stringifies the whole TIn as the request body, so
  // TIn must match the backend schema (UpdateTripSchema) shape directly —
  // NOT a wrapper that nests the body. id is captured in the URL closure.
  const editMutation = useApiMutation<
    {
      id: number;
      vehicle_id: string;
      trip_date: string;
      start_km: string | number;
      end_km: string | number;
      route_from: string;
      route_to: string;
      is_business: number;
      notes: string;
    },
    { message?: string; error?: string }
  >({
    url: ({ id }) => `${API_BASE}/trips/${id}`,
    method: () => "PUT",
    invalidate: ["trips", "vehicles"],
  });

  const deleteMutation = useApiMutation<
    number,
    { message?: string; error?: string }
  >({
    url: (id) => `${API_BASE}/trips/${id}`,
    method: () => "DELETE",
    invalidate: ["trips", "vehicles"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, trip: null });
      alert.success(data?.message || "Smazáno");
    },
  });

  const openEditModal = (trip: Trip) => {
    setEditingTrip(trip);
    setEditForm({
      vehicle_id: String(trip.vehicle_id),
      trip_date: trip.trip_date,
      start_km: trip.start_km,
      end_km: trip.end_km,
      route_from: trip.route_from,
      route_to: trip.route_to,
      is_business: Number(trip.is_business),
      notes: trip.notes || "",
    });
    setShowEditModal(true);
  };

  const handleEditSubmit = async () => {
    if (!editingTrip) return;
    if (
      parseInt(String(editForm.end_km)) <= parseInt(String(editForm.start_km))
    ) {
      alert.error("Konečný stav km musí být větší než počáteční");
      return;
    }

    try {
      const result = await editMutation.mutateAsync({
        id: editingTrip.id,
        vehicle_id: editForm.vehicle_id,
        trip_date: editForm.trip_date,
        start_km: editForm.start_km,
        end_km: editForm.end_km,
        route_from: editForm.route_from,
        route_to: editForm.route_to,
        is_business: editForm.is_business,
        notes: editForm.notes,
      });
      setShowEditModal(false);
      alert.success(result?.message || "Upraveno");
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

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

  const getPeriodName = () =>
    new Date(
      Number(filterPeriod.slice(0, 4)),
      Number(filterPeriod.slice(5, 7)) - 1,
    ).toLocaleString("cs-CZ", { month: "long", year: "numeric" });
  const getSelectedVehicleName = () => {
    if (!filterVehicleId) return null;
    const v = vehicles.find((v) => String(v.id) === filterVehicleId);
    return v ? `${v.spz} - ${v.name}` : null;
  };
  const getSelectedUserName = () => {
    if (!filterUserId) return null;
    const u = tripUsers.find((u) => String(u.id) === filterUserId);
    return u?.name || null;
  };

  const handlePrint = () => {
    const periodName = getPeriodName();

    setTimeout(() => {
      if (printRef.current) {
        const content = printRef.current.innerHTML;
        const printWindow = window.open("", "_blank");
        if (!printWindow) return;
        printWindow.document.write(`
          <!DOCTYPE html>
          <html lang="cs">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Kniha jízd - ${periodName}</title>
            <style>
              * { margin: 0; padding: 0; box-sizing: border-box; }
              body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                font-size: 10px;
                line-height: 1.4;
                color: #000;
                background: #fff;
                padding: 10mm;
              }
              .print-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 15px;
                padding-bottom: 10px;
                border-bottom: 2px solid #333;
              }
              .print-header-left { display: flex; align-items: center; gap: 12px; }
              .print-logo { height: 40px; width: auto; }
              .print-header-text { text-align: left; }
              .print-header-right { text-align: right; }
              .print-header h1 { font-size: 18px; font-weight: 700; margin-bottom: 3px; }
              .print-header .company { font-size: 11px; color: #666; }
              .print-header .period { font-size: 13px; font-weight: 600; color: #333; margin-bottom: 2px; }
              .print-header .filters { font-size: 10px; color: #666; }
              .print-header .generated { font-size: 9px; color: #888; margin-top: 5px; }
              .summary {
                display: flex;
                justify-content: space-around;
                margin-bottom: 15px;
                padding: 10px;
                background: #f5f5f5;
                border: 1px solid #ddd;
              }
              .summary-item { text-align: center; }
              .summary-value { font-size: 14px; font-weight: 700; }
              .summary-label { font-size: 9px; color: #666; }
              table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
              th, td { border: 1px solid #333; padding: 4px 6px; text-align: left; }
              th { background: #333; color: #fff; font-weight: 600; font-size: 9px; text-transform: uppercase; }
              td { font-size: 9px; }
              tr:nth-child(even) { background: #f9f9f9; }
              .text-center { text-align: center; }
              .text-right { text-align: right; }
              tfoot td { background: #eee; font-weight: 600; }
              .badge {
                display: inline-block;
                padding: 1px 4px;
                border-radius: 2px;
                font-size: 8px;
                font-weight: 500;
              }
              .badge-success { background: #dcfce7; color: #16a34a; }
              .badge-warning { background: #fef3c7; color: #d97706; }
              @media print {
                body { padding: 5mm; }
                @page { size: A4 landscape; margin: 5mm; }
                thead { display: table-header-group; }
              }
            </style>
          </head>
          <body>
            ${content}
          </body>
          </html>
        `);
        printWindow.document.close();
        printWindow.onload = () => {
          printWindow.print();
        };
      }
    }, 100);
  };

  const calculateDistance = (): number => {
    const start = parseInt(String(editForm.start_km)) || 0;
    const end = parseInt(String(editForm.end_km)) || 0;
    return end > start ? end - start : 0;
  };

  const totals = {
    count: trips.length,
    total: trips.reduce((sum, t) => sum + t.distance, 0),
    business: trips
      .filter((t) => Number(t.is_business))
      .reduce((sum, t) => sum + t.distance, 0),
  };

  const columns: DataColumn<Trip>[] = [
    {
      key: "trip_date",
      header: "Datum",
      width: "11%",
      mono: true,
      render: (trip) => formatDate(trip.trip_date),
    },
    {
      key: "driver",
      header: "Řidič",
      width: "16%",
      render: (trip) => trip.driver_name,
    },
    {
      key: "vehicle",
      header: "Vozidlo",
      width: "11%",
      mono: true,
      render: (trip) => <StatusChip label={trip.spz} color="default" />,
    },
    {
      key: "route",
      header: "Trasa",
      width: "20%",
      render: (trip) => (
        <Box component="span" sx={{ whiteSpace: "nowrap" }}>
          {trip.route_from} &rarr; {trip.route_to}
        </Box>
      ),
    },
    {
      key: "km",
      header: "Stav km",
      width: "14%",
      mono: true,
      render: (trip) => (
        <Box component="span" sx={{ whiteSpace: "nowrap" }}>
          {formatKm(trip.start_km)} - {formatKm(trip.end_km)}
        </Box>
      ),
    },
    {
      key: "distance",
      header: "Vzdálenost",
      width: "12%",
      mono: true,
      bold: true,
      render: (trip) => `${formatKm(trip.distance)} km`,
    },
    {
      key: "type",
      header: "Typ",
      width: "10%",
      render: (trip) => (
        <StatusChip
          label={trip.is_business ? "Služební" : "Soukromá"}
          color={trip.is_business ? "success" : "warning"}
        />
      ),
    },
    {
      key: "actions",
      header: "Akce",
      width: "10%",
      align: "right",
      render: (trip) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => openEditModal(trip)}
            aria-label="Upravit"
            title="Upravit"
          >
            {EditIcon}
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => setDeleteConfirm({ show: true, trip })}
            aria-label="Smazat"
            title="Smazat"
          >
            {DeleteIcon}
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <PageEnter>
      <Box
        sx={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 2,
          mb: 3,
        }}
      >
        <Typography variant="h4">Správa knihy jízd</Typography>
        <Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
          {trips.length > 0 && (
            <Button
              variant="outlined"
              color="inherit"
              startIcon={PrintIcon}
              onClick={handlePrint}
              title="Tisk knihy jízd"
            >
              Tisk
            </Button>
          )}
          <Button
            component={RouterLink}
            to="/vehicles"
            variant="outlined"
            color="inherit"
          >
            Vozidla
          </Button>
        </Box>
      </Box>

      {/* Filters */}
      <FilterBar>
        <Box sx={{ flex: "0 0 180px" }}>
          <MonthField value={filterPeriod} onChange={setFilterPeriod} />
        </Box>
        <Box sx={{ flex: "0 0 220px" }}>
          <Select
            value={filterVehicleId}
            onChange={setFilterVehicleId}
            options={[
              { value: "", label: "Všechna vozidla" },
              ...vehicles.map((v) => ({
                value: String(v.id),
                label: `${v.spz} - ${v.name}`,
              })),
            ]}
          />
        </Box>
        <Box sx={{ flex: "0 0 220px" }}>
          <Select
            value={filterUserId}
            onChange={setFilterUserId}
            options={[
              { value: "", label: "Všichni řidiči" },
              ...tripUsers.map((u) => ({
                value: String(u.id),
                label: u.name,
              })),
            ]}
          />
        </Box>
      </FilterBar>

      {/* Stats Cards */}
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: {
            xs: "1fr",
            sm: "repeat(3, 1fr)",
          },
          gap: 2,
        }}
      >
        <StatCard
          label="Počet jízd"
          value={totals.count}
          icon={TripsIcon}
          color="info"
        />
        <StatCard
          label="Celkem naježděno"
          value={`${formatKm(totals.total)} km`}
          icon={TotalIcon}
          color="default"
        />
        <StatCard
          label="Služební km"
          value={`${formatKm(totals.business)} km`}
          icon={BusinessIcon}
          color="success"
        />
      </Box>

      {/* Trips Table */}
      <Card sx={{ mt: 3 }}>
        {isPending ? (
          <LoadingState />
        ) : (
          <DataTable<Trip>
            columns={columns}
            rows={trips}
            rowKey={(trip) => trip.id}
            empty={
              <EmptyState title="Žádné záznamy jízd pro vybrané období." />
            }
          />
        )}
      </Card>

      {/* Edit Modal */}
      <Modal
        isOpen={showEditModal && !!editingTrip}
        onClose={() => setShowEditModal(false)}
        onSubmit={handleEditSubmit}
        title="Upravit jízdu"
        subtitle={editingTrip?.driver_name}
        loading={editMutation.isPending}
        maxWidth="lg"
      >
        {editingTrip && (
          <>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                gap: 2,
              }}
            >
              <Field label="Vozidlo">
                <Select
                  value={editForm.vehicle_id}
                  onChange={(value) =>
                    setEditForm({ ...editForm, vehicle_id: value })
                  }
                  options={vehicles.map((v) => ({
                    value: String(v.id),
                    label: `${v.spz} - ${v.name}`,
                  }))}
                />
              </Field>

              <Field label="Datum jízdy">
                <DateField
                  value={editForm.trip_date}
                  onChange={(val) =>
                    setEditForm({ ...editForm, trip_date: val })
                  }
                />
              </Field>
            </Box>

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr 1fr" },
                gap: 2,
              }}
            >
              <Field label="Počáteční stav km">
                <TextField
                  type="number"
                  inputMode="numeric"
                  value={editForm.start_km}
                  onChange={(e) =>
                    setEditForm({ ...editForm, start_km: e.target.value })
                  }
                  slotProps={{ htmlInput: { min: 0 } }}
                />
              </Field>

              <Field label="Konečný stav km">
                <TextField
                  type="number"
                  inputMode="numeric"
                  value={editForm.end_km}
                  onChange={(e) =>
                    setEditForm({ ...editForm, end_km: e.target.value })
                  }
                  slotProps={{ htmlInput: { min: 0 } }}
                />
              </Field>

              <Field label="Vzdálenost">
                <TextField
                  type="text"
                  value={`${formatKm(calculateDistance())} km`}
                  disabled
                  slotProps={{ htmlInput: { readOnly: true } }}
                />
              </Field>
            </Box>

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                gap: 2,
              }}
            >
              <Field label="Místo odjezdu">
                <TextField
                  type="text"
                  value={editForm.route_from}
                  onChange={(e) =>
                    setEditForm({ ...editForm, route_from: e.target.value })
                  }
                />
              </Field>

              <Field label="Místo příjezdu">
                <TextField
                  type="text"
                  value={editForm.route_to}
                  onChange={(e) =>
                    setEditForm({ ...editForm, route_to: e.target.value })
                  }
                />
              </Field>
            </Box>

            <Field label="Typ jízdy">
              <Select
                value={String(editForm.is_business)}
                onChange={(value) =>
                  setEditForm({ ...editForm, is_business: parseInt(value) })
                }
                options={[
                  { value: "1", label: "Služební" },
                  { value: "0", label: "Soukromá" },
                ]}
              />
            </Field>

            <Field label="Poznámky">
              <TextField
                multiline
                minRows={2}
                value={editForm.notes}
                onChange={(e) =>
                  setEditForm({ ...editForm, notes: e.target.value })
                }
              />
            </Field>
          </>
        )}
      </Modal>

      {/* Delete Confirmation */}
      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, trip: null })}
        onConfirm={handleDelete}
        title="Smazat záznam"
        message={
          deleteConfirm.trip
            ? `Opravdu chcete smazat záznam jízdy z ${formatDate(deleteConfirm.trip.trip_date)}?`
            : ""
        }
        confirmText="Smazat"
        confirmVariant="danger"
        loading={deleteMutation.isPending}
      />

      {/* Hidden Print Content */}
      {trips.length > 0 && (
        <div ref={printRef} style={{ display: "none" }}>
          <div className="print-header">
            <div className="print-header-left">
              <img
                src="/api/admin/company-settings/logo?variant=light"
                alt=""
                className="print-logo"
              />
              <div className="print-header-text">
                <h1>KNIHA JÍZD</h1>
                <div className="company">{companyName}</div>
              </div>
            </div>
            <div className="print-header-right">
              <div className="period">{getPeriodName()}</div>
              {getSelectedVehicleName() && (
                <div className="filters">
                  Vozidlo: {getSelectedVehicleName()}
                </div>
              )}
              {getSelectedUserName() && (
                <div className="filters">Řidič: {getSelectedUserName()}</div>
              )}
              <div className="generated">
                Vygenerováno: {new Date().toLocaleString("cs-CZ")}
              </div>
            </div>
          </div>

          <div className="summary">
            <div className="summary-item">
              <div className="summary-value">{totals.count}</div>
              <div className="summary-label">Počet jízd</div>
            </div>
            <div className="summary-item">
              <div className="summary-value">{formatKm(totals.total)} km</div>
              <div className="summary-label">Celkem</div>
            </div>
            <div className="summary-item">
              <div className="summary-value">
                {formatKm(totals.business)} km
              </div>
              <div className="summary-label">Služební</div>
            </div>
            <div className="summary-item">
              <div className="summary-value">
                {formatKm(totals.total - totals.business)} km
              </div>
              <div className="summary-label">Soukromé</div>
            </div>
          </div>

          <table>
            <thead>
              <tr>
                <th style={{ width: "70px" }}>Datum</th>
                <th style={{ width: "80px" }}>Řidič</th>
                <th style={{ width: "70px" }}>Vozidlo</th>
                <th>Trasa</th>
                <th style={{ width: "70px" }} className="text-right">
                  Stav km
                </th>
                <th style={{ width: "60px" }} className="text-right">
                  Vzdálenost
                </th>
                <th style={{ width: "55px" }} className="text-center">
                  Typ
                </th>
                <th>Poznámka</th>
              </tr>
            </thead>
            <tbody>
              {trips.map((trip) => (
                <tr key={trip.id}>
                  <td>{formatDate(trip.trip_date)}</td>
                  <td>{trip.driver_name}</td>
                  <td>{trip.spz}</td>
                  <td>
                    {trip.route_from} &rarr; {trip.route_to}
                  </td>
                  <td className="text-right">
                    {formatKm(trip.start_km)} - {formatKm(trip.end_km)}
                  </td>
                  <td className="text-right">
                    <strong>{formatKm(trip.distance)} km</strong>
                  </td>
                  <td className="text-center">
                    <span
                      className={`badge ${trip.is_business ? "badge-success" : "badge-warning"}`}
                    >
                      {trip.is_business ? "Služební" : "Soukromá"}
                    </span>
                  </td>
                  <td>{trip.notes || ""}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr>
                <td colSpan={5} className="text-right">
                  Celkem:
                </td>
                <td className="text-right">
                  <strong>{formatKm(totals.total)} km</strong>
                </td>
                <td colSpan={2}></td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </PageEnter>
  );
}
