import { useState } 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 { formatDate } from "../utils/attendanceHelpers";
import { formatKm, todayLocalStr } from "../utils/formatters";
import apiFetch from "../utils/api";
import {
  tripListOptions,
  tripStatsOptions,
  tripVehiclesOptions,
  type BackendTrip,
} from "../lib/queries/trips";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { useApiMutation } from "../lib/queries/mutations";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  Select,
  DateField,
  StatusChip,
  LoadingState,
  StatCard,
  PageEnter,
  type DataColumn,
} from "../ui";

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;
}

const PlusIcon = (
  <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>
);
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>
);
const PrivateIcon = (
  <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>
);

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

  // "Poslední jízdy" widget — only the 10 newest rows are shown, so fetch
  // exactly those; the stat cards come from the server-side stats endpoint
  // (computed over the whole filtered set, not one page).
  const { items: trips, isPending: tripsLoading } =
    usePaginatedQuery<BackendTrip>(tripListOptions({ perPage: 10 }));

  // Stat cards are a personal "this month" summary — the header subtitle
  // shows the current month, so the stats query is scoped to match it.
  const now = new Date();
  const { data: stats } = useQuery(
    tripStatsOptions({ month: now.getMonth() + 1, year: now.getFullYear() }),
  );

  const { data: vehiclesData } = useQuery(tripVehiclesOptions());
  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: todayLocalStr(),
    start_km: "",
    end_km: "",
    route_from: "",
    route_to: "",
    is_business: 1,
    notes: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [, setLastKm] = useState(0);

  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 });
    },
  });

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

  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);
    setForm({
      vehicle_id: "",
      trip_date: todayLocalStr(),
      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), 10) <= parseInt(String(form.start_km), 10)
    ) {
      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), 10) || 0;
    const end = parseInt(String(form.end_km), 10) || 0;
    return end > start ? end - start : 0;
  };

  if (tripsLoading) {
    return <LoadingState />;
  }

  const totals = {
    count: stats?.count ?? 0,
    total: stats?.total_km ?? 0,
    business: stats?.business_km ?? 0,
    private: stats?.private_km ?? 0,
  };

  const recentTrips = trips;

  const columns: DataColumn<BackendTrip>[] = [
    {
      key: "trip_date",
      header: "Datum",
      width: "12%",
      mono: true,
      render: (trip) => formatDate(trip.trip_date),
    },
    {
      key: "vehicle",
      header: "Vozidlo",
      width: "12%",
      render: (trip) => (
        <StatusChip label={trip.vehicles?.spz ?? ""} color="default" />
      ),
    },
    {
      key: "driver",
      header: "Řidič",
      width: "16%",
      render: (trip) =>
        trip.users ? `${trip.users.first_name} ${trip.users.last_name}` : "",
    },
    {
      key: "route",
      header: "Trasa",
      width: "22%",
      render: (trip) => (
        <Box component="span" sx={{ whiteSpace: "nowrap" }}>
          {trip.route_from} &rarr; {trip.route_to}
        </Box>
      ),
    },
    {
      key: "distance",
      header: "Vzdálenost",
      width: "12%",
      mono: true,
      bold: true,
      render: (trip) =>
        `${formatKm(trip.distance ?? trip.end_km - trip.start_km)} km`,
    },
    {
      key: "type",
      header: "Typ",
      width: "12%",
      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, tripId: trip.id })}
            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,
        }}
      >
        <Box>
          <Typography variant="h4">Kniha jízd</Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
            {new Date().toLocaleDateString("cs-CZ", {
              month: "long",
              year: "numeric",
            })}
          </Typography>
        </Box>
        <Button startIcon={PlusIcon} onClick={openCreateModal}>
          Přidat jízdu
        </Button>
      </Box>

      {/* Stats Cards */}
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: {
            xs: "1fr",
            sm: "1fr 1fr",
            lg: "repeat(4, 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í"
          value={`${formatKm(totals.business)} km`}
          icon={BusinessIcon}
          color="success"
        />
        <StatCard
          label="Soukromé"
          value={`${formatKm(totals.private)} km`}
          icon={PrivateIcon}
          color="warning"
        />
      </Box>

      {/* Recent Trips */}
      <Card sx={{ mt: 3 }}>
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            mb: 2,
          }}
        >
          <Typography variant="h6">Poslední jízdy</Typography>
          <Button
            component={RouterLink}
            to="/trips/history"
            variant="outlined"
            color="inherit"
            size="small"
          >
            Zobrazit historii
          </Button>
        </Box>
        <DataTable<BackendTrip>
          columns={columns}
          rows={recentTrips}
          rowKey={(trip) => trip.id}
          empty={
            <Box sx={{ textAlign: "center", py: 6 }}>
              <Typography color="text.secondary" gutterBottom>
                Zatím nemáte žádné záznamy jízd.
              </Typography>
              <Button startIcon={PlusIcon} onClick={openCreateModal}>
                Přidat první jízdu
              </Button>
            </Box>
          }
        />
      </Card>

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={editingTrip ? "Upravit jízdu" : "Přidat jízdu"}
        loading={submitMutation.isPending}
        maxWidth="md"
      >
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
            gap: 2,
          }}
        >
          <Field label="Vozidlo" required error={errors.vehicle_id}>
            <Select
              value={form.vehicle_id}
              onChange={(value) => {
                handleVehicleChange(value);
                setErrors((prev) => ({ ...prev, vehicle_id: "" }));
              }}
              error={!!errors.vehicle_id}
              options={[
                { value: "", label: "Vyberte vozidlo" },
                ...vehicles.map((v) => ({
                  value: String(v.id),
                  label: `${v.spz} - ${v.name}`,
                })),
              ]}
            />
          </Field>

          <Field label="Datum jízdy" required error={errors.trip_date}>
            <DateField
              value={form.trip_date}
              onChange={(val) => {
                setForm({ ...form, trip_date: val });
                setErrors((prev) => ({ ...prev, trip_date: "" }));
              }}
            />
          </Field>
        </Box>

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

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

          <Field label="Místo příjezdu" required error={errors.route_to}>
            <TextField
              type="text"
              value={form.route_to}
              error={!!errors.route_to}
              onChange={(e) => {
                setForm({ ...form, route_to: e.target.value });
                setErrors((prev) => ({ ...prev, route_to: "" }));
              }}
              placeholder="Např. Brno"
            />
          </Field>
        </Box>

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

        <Field label="Poznámky">
          <TextField
            multiline
            minRows={2}
            value={form.notes}
            onChange={(e) => setForm({ ...form, notes: e.target.value })}
            placeholder="Volitelné poznámky..."
          />
        </Field>
      </Modal>

      <ConfirmDialog
        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"
        confirmVariant="danger"
        loading={deleteMutation.isPending}
      />
    </PageEnter>
  );
}
