import { useState, useEffect, useCallback, useRef } from "react";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import { Link } from "react-router-dom";
import Forbidden from "../components/Forbidden";
import { motion, AnimatePresence } from "framer-motion";
import ConfirmModal from "../components/ConfirmModal";

import AdminDatePicker from "../components/AdminDatePicker";
import FormField from "../components/FormField";
import useModalLock from "../hooks/useModalLock";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import apiFetch from "../utils/api";
const API_BASE = "/api/admin";

interface Vehicle {
  id: number | string;
  spz: string;
  name: string;
}

interface UserShort {
  id: number | string;
  name: string;
}

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 BackendTrip {
  id: number;
  vehicle_id: number;
  user_id: number;
  trip_date: string;
  start_km: number;
  end_km: number;
  distance: number | null;
  route_from: string;
  route_to: string;
  is_business: boolean;
  notes: string | null;
  users: { id: number; first_name: string; last_name: string };
  vehicles: { id: number; name: string; spz: 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}` : "",
  };
}

export default function TripsAdmin() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const [loading, setLoading] = useState(true);
  const [companyName, setCompanyName] = useState("");
  const [filterMonth, setFilterMonth] = useState(() =>
    String(new Date().getMonth() + 1),
  );
  const [filterYear, setFilterYear] = useState(() =>
    String(new Date().getFullYear()),
  );
  const [filterVehicleId, setFilterVehicleId] = useState("");
  const [filterUserId, setFilterUserId] = useState("");
  const [trips, setTrips] = useState<Trip[]>([]);
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [users, setUsers] = useState<UserShort[]>([]);
  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 });

  // Fetch vehicles and users once on mount
  useEffect(() => {
    const fetchLookups = async () => {
      try {
        const [vRes, uRes, csRes] = await Promise.all([
          apiFetch(`${API_BASE}/vehicles`),
          apiFetch(`${API_BASE}/trips/users`),
          apiFetch(`${API_BASE}/company-settings`),
        ]);
        const vJson = await vRes.json();
        const uJson = await uRes.json();
        const csJson = await csRes.json();
        if (vJson.success) setVehicles(vJson.data);
        if (csJson.success) setCompanyName(csJson.data.company_name || "");
        if (uJson.success) {
          setUsers(uJson.data);
        }
      } catch {
        // silently fail, filters will just be empty
      }
    };
    fetchLookups();
  }, []);

  const fetchData = useCallback(
    async (showLoading = true) => {
      if (showLoading) setLoading(true);
      try {
        let url = `${API_BASE}/trips?limit=1000&month=${filterMonth}&year=${filterYear}`;
        if (filterVehicleId) url += `&vehicle_id=${filterVehicleId}`;
        if (filterUserId) url += `&user_id=${filterUserId}`;

        const response = await apiFetch(url);
        const result = await response.json();
        if (result.success) {
          const mapped = (result.data as BackendTrip[]).map(mapTrip);
          setTrips(mapped);
        }
      } catch {
        alert.error("Nepodařilo se načíst data");
      } finally {
        if (showLoading) setLoading(false);
      }
    },
    [filterMonth, filterYear, filterVehicleId, filterUserId, alert],
  );

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  useModalLock(showEditModal);

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

  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 response = await apiFetch(`${API_BASE}/trips/${editingTrip.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editForm),
      });

      const result = await response.json();

      if (result.success) {
        setShowEditModal(false);
        await fetchData(false);
        await new Promise((resolve) => setTimeout(resolve, 300));
        alert.success(result.message);
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.trip) return;

    try {
      const response = await apiFetch(
        `${API_BASE}/trips/${deleteConfirm.trip.id}`,
        {
          method: "DELETE",
        },
      );

      const result = await response.json();

      if (result.success) {
        setDeleteConfirm({ show: false, trip: null });
        await fetchData(false);
        alert.success(result.message);
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    }
  };

  const getPeriodName = () =>
    new Date(Number(filterYear), Number(filterMonth) - 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 = users.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),
  };

  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">Správa knihy jízd</h1>
        </div>
        <div className="admin-page-actions">
          {trips.length > 0 && (
            <button
              onClick={handlePrint}
              className="admin-btn admin-btn-secondary"
              title="Tisk knihy jízd"
            >
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                style={{ marginRight: "0.5rem" }}
              >
                <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>
              Tisk
            </button>
          )}
          <Link to="/vehicles" className="admin-btn admin-btn-secondary">
            Vozidla
          </Link>
        </div>
      </motion.div>

      {/* Filters */}
      <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">
          <div className="admin-form-row admin-form-row-4">
            <FormField label="Měsíc" style={{ marginBottom: 0 }}>
              <select
                value={filterMonth}
                onChange={(e) => setFilterMonth(e.target.value)}
                className="admin-form-select"
              >
                {Array.from({ length: 12 }, (_, i) => (
                  <option key={i + 1} value={i + 1}>
                    {new Date(2000, i).toLocaleString("cs-CZ", {
                      month: "long",
                    })}
                  </option>
                ))}
              </select>
            </FormField>
            <FormField label="Rok" style={{ marginBottom: 0 }}>
              <select
                value={filterYear}
                onChange={(e) => setFilterYear(e.target.value)}
                className="admin-form-select"
              >
                {Array.from({ length: 5 }, (_, i) => {
                  const y = new Date().getFullYear() - 2 + i;
                  return (
                    <option key={y} value={y}>
                      {y}
                    </option>
                  );
                })}
              </select>
            </FormField>
            <FormField label="Vozidlo" style={{ marginBottom: 0 }}>
              <select
                value={filterVehicleId}
                onChange={(e) => setFilterVehicleId(e.target.value)}
                className="admin-form-select"
              >
                <option value="">Všechna vozidla</option>
                {vehicles.map((v) => (
                  <option key={v.id} value={v.id}>
                    {v.spz} - {v.name}
                  </option>
                ))}
              </select>
            </FormField>
            <FormField label="Řidič" style={{ marginBottom: 0 }}>
              <select
                value={filterUserId}
                onChange={(e) => setFilterUserId(e.target.value)}
                className="admin-form-select"
              >
                <option value="">Všichni řidiči</option>
                {users.map((u) => (
                  <option key={u.id} value={u.id}>
                    {u.name}
                  </option>
                ))}
              </select>
            </FormField>
          </div>
        </div>
      </motion.div>

      <motion.div
        className="admin-grid admin-grid-3 mt-6"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.08 }}
      >
        <div className="admin-stat-card info">
          <div className="admin-stat-icon info">
            <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>
          </div>
          <div className="admin-stat-content">
            <span className="admin-stat-value">{totals.count}</span>
            <span className="admin-stat-label">Počet jízd</span>
          </div>
        </div>
        <div className="admin-stat-card">
          <div className="admin-stat-icon">
            <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>
          </div>
          <div className="admin-stat-content">
            <span className="admin-stat-value">
              {formatKm(totals.total)} km
            </span>
            <span className="admin-stat-label">Celkem naježděno</span>
          </div>
        </div>
        <div className="admin-stat-card success">
          <div className="admin-stat-icon success">
            <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>
          </div>
          <div className="admin-stat-content">
            <span className="admin-stat-value">
              {formatKm(totals.business)} km
            </span>
            <span className="admin-stat-label">Služební km</span>
          </div>
        </div>
      </motion.div>

      {/* Trips Table */}
      <motion.div
        className="admin-card mt-6"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.12 }}
      >
        <div className="admin-card-body">
          {loading && (
            <div className="admin-skeleton" style={{ gap: "1.25rem" }}>
              {[0, 1, 2, 3, 4].map((i) => (
                <div key={i} className="admin-skeleton-row">
                  <div className="admin-skeleton-line w-1/4" />
                  <div className="admin-skeleton-line w-1/3" />
                  <div className="admin-skeleton-line w-1/4" />
                </div>
              ))}
            </div>
          )}
          {!loading && trips.length === 0 && (
            <div className="admin-empty-state">
              <p>Žádné záznamy jízd pro vybrané období.</p>
            </div>
          )}
          {!loading && trips.length > 0 && (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Datum</th>
                    <th>Řidič</th>
                    <th>Vozidlo</th>
                    <th>Trasa</th>
                    <th>Stav km</th>
                    <th>Vzdálenost</th>
                    <th>Typ</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {trips.map((trip) => (
                    <tr key={trip.id}>
                      <td className="admin-mono">
                        {formatDate(trip.trip_date)}
                      </td>
                      <td>{trip.driver_name}</td>
                      <td>
                        <span className="admin-badge">{trip.spz}</span>
                      </td>
                      <td>
                        <span style={{ whiteSpace: "nowrap" }}>
                          {trip.route_from} &rarr; {trip.route_to}
                        </span>
                      </td>
                      <td className="admin-mono">
                        <span style={{ whiteSpace: "nowrap" }}>
                          {formatKm(trip.start_km)} - {formatKm(trip.end_km)}
                        </span>
                      </td>
                      <td className="admin-mono">
                        <strong>{formatKm(trip.distance)} km</strong>
                      </td>
                      <td>
                        <span
                          className={`admin-badge ${trip.is_business ? "admin-badge-success" : "admin-badge-warning"}`}
                        >
                          {trip.is_business ? "Služební" : "Soukromá"}
                        </span>
                      </td>
                      <td>
                        <div className="admin-table-actions">
                          <button
                            onClick={() => openEditModal(trip)}
                            className="admin-btn-icon"
                            title="Upravit"
                            aria-label="Upravit"
                          >
                            <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>
                          </button>
                          <button
                            onClick={() =>
                              setDeleteConfirm({ show: true, trip })
                            }
                            className="admin-btn-icon danger"
                            title="Smazat"
                            aria-label="Smazat"
                          >
                            <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>

      {/* Edit Modal */}
      <AnimatePresence>
        {showEditModal && editingTrip && (
          <motion.div
            className="admin-modal-overlay"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <div
              className="admin-modal-backdrop"
              onClick={() => setShowEditModal(false)}
            />
            <motion.div
              className="admin-modal admin-modal-lg"
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              transition={{ duration: 0.2 }}
            >
              <div className="admin-modal-header">
                <h2 className="admin-modal-title">Upravit jízdu</h2>
                <p
                  style={{
                    color: "var(--text-secondary)",
                    marginTop: "0.25rem",
                  }}
                >
                  {editingTrip.driver_name}
                </p>
              </div>

              <div className="admin-modal-body">
                <div className="admin-form">
                  <div className="admin-form-row">
                    <FormField label="Vozidlo">
                      <select
                        value={editForm.vehicle_id}
                        onChange={(e) =>
                          setEditForm({
                            ...editForm,
                            vehicle_id: e.target.value,
                          })
                        }
                        className="admin-form-select"
                      >
                        {vehicles.map((v) => (
                          <option key={v.id} value={v.id}>
                            {v.spz} - {v.name}
                          </option>
                        ))}
                      </select>
                    </FormField>

                    <FormField label="Datum jízdy">
                      <AdminDatePicker
                        mode="date"
                        value={editForm.trip_date}
                        onChange={(val: string) =>
                          setEditForm({ ...editForm, trip_date: val })
                        }
                      />
                    </FormField>
                  </div>

                  <div className="admin-form-row">
                    <FormField label="Počáteční stav km">
                      <input
                        type="number"
                        inputMode="numeric"
                        value={editForm.start_km}
                        onChange={(e) =>
                          setEditForm({ ...editForm, start_km: e.target.value })
                        }
                        className="admin-form-input"
                        min="0"
                      />
                    </FormField>

                    <FormField label="Konečný stav km">
                      <input
                        type="number"
                        inputMode="numeric"
                        value={editForm.end_km}
                        onChange={(e) =>
                          setEditForm({ ...editForm, end_km: e.target.value })
                        }
                        className="admin-form-input"
                        min="0"
                      />
                    </FormField>

                    <FormField label="Vzdálenost">
                      <input
                        type="text"
                        value={`${formatKm(calculateDistance())} km`}
                        className="admin-form-input"
                        readOnly
                        disabled
                      />
                    </FormField>
                  </div>

                  <div className="admin-form-row">
                    <FormField label="Místo odjezdu">
                      <input
                        type="text"
                        value={editForm.route_from}
                        onChange={(e) =>
                          setEditForm({
                            ...editForm,
                            route_from: e.target.value,
                          })
                        }
                        className="admin-form-input"
                      />
                    </FormField>

                    <FormField label="Místo příjezdu">
                      <input
                        type="text"
                        value={editForm.route_to}
                        onChange={(e) =>
                          setEditForm({ ...editForm, route_to: e.target.value })
                        }
                        className="admin-form-input"
                      />
                    </FormField>
                  </div>

                  <FormField label="Typ jízdy">
                    <select
                      value={editForm.is_business}
                      onChange={(e) =>
                        setEditForm({
                          ...editForm,
                          is_business: parseInt(e.target.value),
                        })
                      }
                      className="admin-form-select"
                    >
                      <option value={1}>Služební</option>
                      <option value={0}>Soukromá</option>
                    </select>
                  </FormField>

                  <FormField label="Poznámky">
                    <textarea
                      value={editForm.notes}
                      onChange={(e) =>
                        setEditForm({ ...editForm, notes: e.target.value })
                      }
                      className="admin-form-textarea"
                      rows={2}
                    />
                  </FormField>
                </div>
              </div>

              <div className="admin-modal-footer">
                <button
                  type="button"
                  onClick={() => setShowEditModal(false)}
                  className="admin-btn admin-btn-secondary"
                >
                  Zrušit
                </button>
                <button
                  type="button"
                  onClick={handleEditSubmit}
                  className="admin-btn admin-btn-primary"
                >
                  Uložit
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Delete Confirmation */}
      <ConfirmModal
        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"
      />

      {/* 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>
      )}
    </div>
  );
}
