import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import { Link } from "react-router-dom";
import { motion } from "framer-motion";

import AdminDatePicker from "../components/AdminDatePicker";
import ConfirmModal from "../components/ConfirmModal";
import FormModal from "../components/FormModal";
import FormField from "../components/FormField";
import Forbidden from "../components/Forbidden";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import apiFetch from "../utils/api";
import {
  tripListOptions,
  tripVehiclesOptions,
  type BackendTrip,
  type TripVehicle,
} from "../lib/queries/trips";
import { useApiMutation } from "../lib/queries/mutations";
const API_BASE = "/api/admin";

interface TripForm {
  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;
}

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

  const { data: tripsData, isPending: tripsLoading } = useQuery(
    tripListOptions({}),
  );
  const { data: vehiclesData } = useQuery(tripVehiclesOptions());

  const trips = tripsData ?? [];
  const vehicles = vehiclesData ?? [];

  const [showModal, setShowModal] = useState(false);
  const [editingTrip, setEditingTrip] = useState<BackendTrip | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    tripId: number | null;
  }>({ show: false, tripId: null });
  const [form, setForm] = useState<TripForm>({
    vehicle_id: "",
    trip_date: new Date().toISOString().split("T")[0],
    start_km: "",
    end_km: "",
    route_from: "",
    route_to: "",
    is_business: 1,
    notes: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [, setLastKm] = useState(0);

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

  const submitMutation = useApiMutation<
    TripForm,
    { message?: string; error?: string }
  >({
    url: (formData) =>
      editingTrip ? `${API_BASE}/trips/${editingTrip.id}` : `${API_BASE}/trips`,
    method: () => (editingTrip ? "PUT" : "POST"),
    invalidate: ["trips", "vehicles"],
    onSuccess: (data) => {
      setShowModal(false);
      alert.success(data?.message || "Hotovo");
    },
  });

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

  const fetchLastKm = async (vehicleId: string) => {
    if (!vehicleId) {
      setLastKm(0);
      return;
    }
    try {
      const response = await apiFetch(`${API_BASE}/trips/last-km/${vehicleId}`);
      const result = await response.json();
      if (result.success) {
        const km = result.data?.last_km || 0;
        setLastKm(km);
        if (!editingTrip) {
          setForm((prev) => ({ ...prev, start_km: km }));
        }
        return;
      }
    } catch {
      /* fallback below */
    }
    setLastKm(0);
  };

  const openCreateModal = () => {
    setEditingTrip(null);
    const today = new Date().toISOString().split("T")[0];
    setForm({
      vehicle_id: "",
      trip_date: today,
      start_km: "",
      end_km: "",
      route_from: "",
      route_to: "",
      is_business: 1,
      notes: "",
    });
    setLastKm(0);
    setErrors({});
    setShowModal(true);
  };

  const openEditModal = (trip: BackendTrip) => {
    setEditingTrip(trip);
    setForm({
      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 || "",
    });
    setLastKm(trip.start_km);
    setErrors({});
    setShowModal(true);
  };

  const handleVehicleChange = (vehicleId: string) => {
    setForm((prev) => ({ ...prev, vehicle_id: vehicleId }));
    fetchLastKm(vehicleId);
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!form.vehicle_id) newErrors.vehicle_id = "Vyberte vozidlo";
    if (!form.trip_date) newErrors.trip_date = "Zadejte datum";
    if (!form.start_km) newErrors.start_km = "Zadejte počáteční km";
    if (!form.end_km) newErrors.end_km = "Zadejte konečný km";
    if (
      form.start_km &&
      form.end_km &&
      parseInt(String(form.end_km)) <= parseInt(String(form.start_km))
    ) {
      newErrors.end_km = "Musí být větší než počáteční";
    }
    if (!form.route_from) newErrors.route_from = "Zadejte místo odjezdu";
    if (!form.route_to) newErrors.route_to = "Zadejte místo příjezdu";
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;
    try {
      await submitMutation.mutateAsync(form);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleDelete = async (tripId: number) => {
    try {
      await deleteMutation.mutateAsync(tripId);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

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

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

  const totals = trips.reduce(
    (acc, t) => {
      const dist = t.distance ?? t.end_km - t.start_km;
      acc.count++;
      acc.total += dist;
      if (t.is_business) acc.business += dist;
      else acc.private += dist;
      return acc;
    },
    { total: 0, business: 0, private: 0, count: 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">Kniha jízd</h1>
          <p className="admin-page-subtitle">
            {new Date().toLocaleDateString("cs-CZ", {
              month: "long",
              year: "numeric",
            })}
          </p>
        </div>
        <div className="admin-page-actions">
          <button
            onClick={openCreateModal}
            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>
            Přidat jízdu
          </button>
        </div>
      </motion.div>

      {/* Stats Cards */}
      <motion.div
        className="admin-grid admin-grid-4"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.06 }}
      >
        <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í</span>
          </div>
        </div>

        <div className="admin-stat-card warning">
          <div className="admin-stat-icon warning">
            <svg
              width="22"
              height="22"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
              <polyline points="9 22 9 12 15 12 15 22" />
            </svg>
          </div>
          <div className="admin-stat-content">
            <span className="admin-stat-value">
              {formatKm(totals.private)} km
            </span>
            <span className="admin-stat-label">Soukromé</span>
          </div>
        </div>
      </motion.div>

      {/* Recent Trips */}
      <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-header flex-between">
          <h2 className="admin-card-title">Poslední jízdy</h2>
          <Link
            to="/trips/history"
            className="admin-btn admin-btn-secondary admin-btn-sm"
          >
            Zobrazit historii
          </Link>
        </div>
        <div className="admin-card-body">
          {trips.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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                  <polyline points="14 2 14 8 20 8" />
                  <line x1="16" y1="13" x2="8" y2="13" />
                  <line x1="16" y1="17" x2="8" y2="17" />
                </svg>
              </div>
              <p>Zatím nemáte žádné záznamy jízd.</p>
              <button
                onClick={openCreateModal}
                className="admin-btn admin-btn-primary"
              >
                Přidat první jízdu
              </button>
            </div>
          ) : (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Datum</th>
                    <th>Vozidlo</th>
                    <th>Řidič</th>
                    <th>Trasa</th>
                    <th>Vzdálenost</th>
                    <th>Typ</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {trips.slice(0, 10).map((trip) => (
                    <tr key={trip.id}>
                      <td className="admin-mono">
                        {formatDate(trip.trip_date)}
                      </td>
                      <td>
                        <span className="admin-badge">
                          {trip.vehicles?.spz ?? ""}
                        </span>
                      </td>
                      <td>
                        {trip.users
                          ? `${trip.users.first_name} ${trip.users.last_name}`
                          : ""}
                      </td>
                      <td>
                        <span style={{ whiteSpace: "nowrap" }}>
                          {trip.route_from} &rarr; {trip.route_to}
                        </span>
                      </td>
                      <td className="admin-mono">
                        <strong>
                          {formatKm(
                            trip.distance ?? trip.end_km - trip.start_km,
                          )}{" "}
                          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, tripId: trip.id })
                            }
                            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>

      {/* Add/Edit Modal */}
      <FormModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={editingTrip ? "Upravit jízdu" : "Přidat jízdu"}
        loading={submitMutation.isPending}
        size="lg"
      >
        <div className="admin-form">
          <div className="admin-form-row">
            <FormField label="Vozidlo" error={errors.vehicle_id} required>
              <select
                value={form.vehicle_id}
                onChange={(e) => {
                  handleVehicleChange(e.target.value);
                  setErrors((prev) => ({ ...prev, vehicle_id: "" }));
                }}
                className="admin-form-select"
              >
                <option value="">Vyberte vozidlo</option>
                {vehicles.map((v) => (
                  <option key={v.id} value={v.id}>
                    {v.spz} - {v.name}
                  </option>
                ))}
              </select>
            </FormField>

            <FormField label="Datum jízdy" error={errors.trip_date} required>
              <AdminDatePicker
                mode="date"
                value={form.trip_date}
                onChange={(val: string) => {
                  setForm({ ...form, trip_date: val });
                  setErrors((prev) => ({ ...prev, trip_date: "" }));
                }}
              />
            </FormField>
          </div>

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

            <FormField label="Konečný stav km" error={errors.end_km} required>
              <input
                type="number"
                inputMode="numeric"
                value={form.end_km}
                onChange={(e) => {
                  setForm({ ...form, end_km: e.target.value });
                  setErrors((prev) => ({ ...prev, end_km: "" }));
                }}
                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" error={errors.route_from} required>
              <input
                type="text"
                value={form.route_from}
                onChange={(e) => {
                  setForm({ ...form, route_from: e.target.value });
                  setErrors((prev) => ({ ...prev, route_from: "" }));
                }}
                className="admin-form-input"
                placeholder="Např. Praha"
              />
            </FormField>

            <FormField label="Místo příjezdu" error={errors.route_to} required>
              <input
                type="text"
                value={form.route_to}
                onChange={(e) => {
                  setForm({ ...form, route_to: e.target.value });
                  setErrors((prev) => ({ ...prev, route_to: "" }));
                }}
                className="admin-form-input"
                placeholder="Např. Brno"
              />
            </FormField>
          </div>

          <FormField label="Typ jízdy">
            <select
              value={form.is_business}
              onChange={(e) =>
                setForm({
                  ...form,
                  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={form.notes}
              onChange={(e) => setForm({ ...form, notes: e.target.value })}
              className="admin-form-textarea"
              rows={2}
              placeholder="Volitelné poznámky..."
            />
          </FormField>
        </div>
      </FormModal>

      <ConfirmModal
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, tripId: null })}
        onConfirm={() => handleDelete(deleteConfirm.tripId!)}
        title="Smazat jízdu"
        message="Opravdu chcete smazat tento záznam?"
        confirmText="Smazat"
        cancelText="Zrušit"
        type="danger"
        loading={deleteMutation.isPending}
      />
    </div>
  );
}
