import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
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 { formatKm } from "../utils/formatters";
import { vehicleListOptions } from "../lib/queries/vehicles";
import { useApiMutation } from "../lib/queries/mutations";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  SwitchField,
  StatusChip,
  LoadingState,
  PageEnter,
  type DataColumn,
} from "../ui";

const API_BASE = "/api/admin";

interface Vehicle {
  id: number;
  spz: string;
  name: string;
  brand?: string;
  model?: string;
  initial_km: number;
  current_km: number;
  trip_count: number;
  is_active: boolean | number;
}

interface VehicleForm {
  spz: string;
  name: string;
  brand: string;
  model: string;
  initial_km: number;
  is_active: boolean;
}

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

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

  const { data: vehicles = [], isPending } = useQuery({
    ...vehicleListOptions(),
    select: (data) => data as unknown as Vehicle[],
  });

  const [showModal, setShowModal] = useState(false);
  const [editingVehicle, setEditingVehicle] = useState<Vehicle | null>(null);
  const [form, setForm] = useState<VehicleForm>({
    spz: "",
    name: "",
    brand: "",
    model: "",
    initial_km: 0,
    is_active: true,
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    vehicle: Vehicle | null;
  }>({ show: false, vehicle: null });
  const [saving, setSaving] = useState(false);

  const saveVehicle = useApiMutation<VehicleForm, void>({
    url: () =>
      editingVehicle
        ? `${API_BASE}/vehicles/${editingVehicle.id}`
        : `${API_BASE}/vehicles`,
    method: () => (editingVehicle ? "PUT" : "POST"),
    invalidate: ["vehicles", "trips"],
    onSuccess: () => {
      setShowModal(false);
      alert.success(
        editingVehicle ? "Vozidlo bylo upraveno" : "Vozidlo bylo vytvořeno",
      );
    },
  });

  const deleteVehicle = useApiMutation<number, void>({
    url: (id) => `${API_BASE}/vehicles/${id}`,
    method: () => "DELETE",
    invalidate: ["vehicles", "trips"],
    onSuccess: () => {
      setDeleteConfirm({ show: false, vehicle: null });
      alert.success("Vozidlo bylo smazáno");
    },
  });

  const toggleVehicle = useApiMutation<
    { id: number; is_active: boolean },
    void
  >({
    url: (input) => `${API_BASE}/vehicles/${input.id}`,
    method: () => "PUT",
    invalidate: ["vehicles", "trips"],
    onSuccess: (_data, input) => {
      alert.success(
        input.is_active
          ? "Vozidlo bylo aktivováno"
          : "Vozidlo bylo deaktivováno",
      );
    },
  });

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

  const openCreateModal = () => {
    setEditingVehicle(null);
    setForm({
      spz: "",
      name: "",
      brand: "",
      model: "",
      initial_km: 0,
      is_active: true,
    });
    setErrors({});
    setShowModal(true);
  };

  const openEditModal = (vehicle: Vehicle) => {
    setEditingVehicle(vehicle);
    setForm({
      spz: vehicle.spz,
      name: vehicle.name,
      brand: vehicle.brand || "",
      model: vehicle.model || "",
      initial_km: vehicle.initial_km,
      is_active: Boolean(vehicle.is_active),
    });
    setErrors({});
    setShowModal(true);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (!form.spz) newErrors.spz = "Zadejte SPZ";
    if (!form.name) newErrors.name = "Zadejte název";
    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) return;

    setSaving(true);
    try {
      await saveVehicle.mutateAsync(form);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

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

  const toggleActive = (vehicle: Vehicle) => {
    toggleVehicle.mutate({
      id: vehicle.id,
      is_active: !vehicle.is_active,
    });
  };

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

  const columns: DataColumn<Vehicle>[] = [
    { key: "spz", header: "SPZ", mono: true, bold: true, render: (v) => v.spz },
    { key: "name", header: "Název", render: (v) => v.name },
    {
      key: "brand",
      header: "Značka / Model",
      render: (v) =>
        v.brand || v.model ? `${v.brand || ""} ${v.model || ""}`.trim() : "—",
    },
    {
      key: "initial_km",
      header: "Počáteční km",
      align: "right",
      mono: true,
      render: (v) => `${formatKm(v.initial_km)} km`,
    },
    {
      key: "current_km",
      header: "Aktuální km",
      align: "right",
      mono: true,
      bold: true,
      render: (v) => `${formatKm(v.current_km)} km`,
    },
    {
      key: "trips",
      header: "Počet jízd",
      align: "right",
      mono: true,
      render: (v) => v.trip_count,
    },
    {
      key: "status",
      header: "Stav",
      render: (v) => (
        <StatusChip
          label={v.is_active ? "Aktivní" : "Neaktivní"}
          color={v.is_active ? "success" : "default"}
          onClick={() => toggleActive(v)}
        />
      ),
    },
    {
      key: "actions",
      header: "Akce",
      align: "right",
      render: (v) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => openEditModal(v)}
            aria-label="Upravit"
            title="Upravit"
          >
            {EditIcon}
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => setDeleteConfirm({ show: true, vehicle: v })}
            aria-label="Smazat"
            title="Smazat"
          >
            {DeleteIcon}
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <PageEnter>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          mb: 3,
          flexWrap: "wrap",
          gap: 2,
        }}
      >
        <Typography variant="h4">Správa vozidel</Typography>
        <Button startIcon={PlusIcon} onClick={openCreateModal}>
          Přidat vozidlo
        </Button>
      </Box>

      <Card>
        <DataTable<Vehicle>
          columns={columns}
          rows={vehicles}
          rowKey={(v) => v.id}
          rowInactive={(v) => !v.is_active}
          empty={
            <Box sx={{ textAlign: "center", py: 6 }}>
              <Typography color="text.secondary" gutterBottom>
                Zatím nejsou žádná vozidla.
              </Typography>
              <Button startIcon={PlusIcon} onClick={openCreateModal}>
                Přidat první vozidlo
              </Button>
            </Box>
          }
        />
      </Card>

      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={editingVehicle ? "Upravit vozidlo" : "Přidat vozidlo"}
        loading={saving}
      >
        <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
          <Box sx={{ flex: "1 1 200px" }}>
            <Field label="SPZ" required error={errors.spz}>
              <TextField
                value={form.spz}
                placeholder="1AB 2345"
                error={!!errors.spz}
                onChange={(e) => {
                  setForm({ ...form, spz: e.target.value.toUpperCase() });
                  setErrors((prev) => ({ ...prev, spz: "" }));
                }}
              />
            </Field>
          </Box>
          <Box sx={{ flex: "1 1 200px" }}>
            <Field label="Název" required error={errors.name}>
              <TextField
                value={form.name}
                placeholder="Služební #1"
                error={!!errors.name}
                onChange={(e) => {
                  setForm({ ...form, name: e.target.value });
                  setErrors((prev) => ({ ...prev, name: "" }));
                }}
              />
            </Field>
          </Box>
        </Box>

        <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
          <Box sx={{ flex: "1 1 200px" }}>
            <Field label="Značka">
              <TextField
                value={form.brand}
                placeholder="Škoda"
                onChange={(e) => setForm({ ...form, brand: e.target.value })}
              />
            </Field>
          </Box>
          <Box sx={{ flex: "1 1 200px" }}>
            <Field label="Model">
              <TextField
                value={form.model}
                placeholder="Octavia Combi"
                onChange={(e) => setForm({ ...form, model: e.target.value })}
              />
            </Field>
          </Box>
        </Box>

        <Field
          label="Počáteční stav km"
          hint="Stav tachometru při přidání vozidla"
        >
          <TextField
            type="number"
            value={form.initial_km}
            slotProps={{ htmlInput: { min: 0, inputMode: "numeric" } }}
            onChange={(e) =>
              setForm({
                ...form,
                initial_km: parseInt(e.target.value, 10) || 0,
              })
            }
          />
        </Field>

        <SwitchField
          label="Vozidlo je aktivní"
          checked={form.is_active}
          onChange={(v) => setForm({ ...form, is_active: v })}
        />
      </Modal>

      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, vehicle: null })}
        onConfirm={handleDelete}
        title="Smazat vozidlo"
        message={
          deleteConfirm.vehicle
            ? `Opravdu chcete smazat vozidlo ${deleteConfirm.vehicle.spz} - ${deleteConfirm.vehicle.name}?`
            : ""
        }
        confirmText="Smazat"
        confirmVariant="danger"
      />
    </PageEnter>
  );
}
