"use client";

import { type Dispatch, type FormEvent, type MutableRefObject, type ReactNode, type SetStateAction } from "react";
import { createPortal } from "react-dom";

import {
  VEHICLE_COLOR_OPTIONS,
  type VehicleColorKey,
  type VehicleKind,
  type VehicleSummary,
} from "@tracker/shared";

import type { AdminDeviceSummary } from "../../../lib/api";

type UserRole = "admin" | "user";

type VehicleServiceFieldProps = {
  label: string;
  children: ReactNode;
  className?: string;
  labelClassName?: string;
};

function VehicleServiceField({ label, children, className = "", labelClassName = "" }: VehicleServiceFieldProps) {
  return (
    <div className={`vehicle-service-field relative w-full min-w-0 pt-2 ${className}`}>
      <div className={`vehicle-service-field-label absolute top-2 z-[1] px-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-steel ${labelClassName}`}>
        {label}
      </div>
      {children}
    </div>
  );
}

type VehicleEditModalProps = {
  isOpen: boolean;
  overlayRoot: HTMLElement | null;
  panelRef: MutableRefObject<HTMLDivElement | null>;
  selectedVehicle: VehicleSummary | null;
  userRole: UserRole;
  onClose: () => void;
  onSubmit: (event: FormEvent<HTMLFormElement>) => void;
  onDeleteVehicle: () => void;
  editVehicleInspectionDueDate: string;
  setEditVehicleInspectionDueDate: (value: string) => void;
  editVehicleOilChangeDueDate: string;
  setEditVehicleOilChangeDueDate: (value: string) => void;
  editVehicleOilChangeOdometer: string;
  setEditVehicleOilChangeOdometer: (value: string) => void;
  editVehicleOilChangeIntervalKm: string;
  setEditVehicleOilChangeIntervalKm: (value: string) => void;
  editVehicleTireChangedAt: string;
  setEditVehicleTireChangedAt: (value: string) => void;
  editVehicleNextTireChangeDueDate: string;
  setEditVehicleNextTireChangeDueDate: (value: string) => void;
  formatMileageKm: (value?: number | null) => string;
  systemDevices: AdminDeviceSummary[];
  editDeviceImei: string;
  setEditDeviceImei: (value: string) => void;
  editAssignedDeviceId: string;
  setEditAssignedDeviceId: (value: string) => void;
  editDevicePhoneNumber: string;
  setEditDevicePhoneNumber: Dispatch<SetStateAction<string>>;
  editVehicleName: string;
  setEditVehicleName: (value: string) => void;
  editVehiclePlateNumber: string;
  setEditVehiclePlateNumber: (value: string) => void;
  editVehicleKind: VehicleKind;
  setEditVehicleKind: (value: VehicleKind) => void;
  editVehicleColorKey: VehicleColorKey;
  setEditVehicleColorKey: (value: VehicleColorKey) => void;
  previewVehicleColor: string;
  shiftHex: (hex: string, amount: number) => string;
  getDeviceByImei: (imei?: string | null) => AdminDeviceSummary | null;
  getDeviceById: (id?: string | null) => AdminDeviceSummary | null;
};

export function VehicleEditModal({
  isOpen,
  overlayRoot,
  panelRef,
  selectedVehicle,
  userRole,
  onClose,
  onSubmit,
  onDeleteVehicle,
  editVehicleInspectionDueDate,
  setEditVehicleInspectionDueDate,
  editVehicleOilChangeDueDate,
  setEditVehicleOilChangeDueDate,
  editVehicleOilChangeOdometer,
  setEditVehicleOilChangeOdometer,
  editVehicleOilChangeIntervalKm,
  setEditVehicleOilChangeIntervalKm,
  editVehicleTireChangedAt,
  setEditVehicleTireChangedAt,
  editVehicleNextTireChangeDueDate,
  setEditVehicleNextTireChangeDueDate,
  formatMileageKm,
  systemDevices,
  editDeviceImei,
  setEditDeviceImei,
  editAssignedDeviceId,
  setEditAssignedDeviceId,
  editDevicePhoneNumber,
  setEditDevicePhoneNumber,
  editVehicleName,
  setEditVehicleName,
  editVehiclePlateNumber,
  setEditVehiclePlateNumber,
  editVehicleKind,
  setEditVehicleKind,
  editVehicleColorKey,
  setEditVehicleColorKey,
  previewVehicleColor,
  shiftHex,
  getDeviceByImei,
  getDeviceById,
}: VehicleEditModalProps) {
  if (!isOpen || !selectedVehicle || !overlayRoot) {
    return null;
  }

  const nextOilChangeAtMileage = editVehicleOilChangeOdometer.trim() && editVehicleOilChangeIntervalKm.trim()
    ? String(Math.round(Number(editVehicleOilChangeOdometer) + Number(editVehicleOilChangeIntervalKm)))
    : "";

  return createPortal((
    <div
      className="vehicle-edit-modal-backdrop fixed inset-0 z-[960] flex items-start justify-center overflow-y-auto bg-slate-950/38 px-3 py-6 backdrop-blur-[3px] sm:items-center"
      onClick={onClose}
    >
      <div
        ref={panelRef}
        className="vehicle-edit-modal-panel panel relative my-auto max-h-[calc(100vh-3rem)] w-full max-w-[560px] overflow-x-hidden overflow-y-auto rounded-[1.75rem] px-5 pb-5 pt-5 shadow-panel sm:px-6 sm:pb-6 sm:pt-6"
        onClick={(event) => event.stopPropagation()}
      >
        <button
          type="button"
          onClick={onClose}
          className="vehicle-edit-modal-close absolute right-5 top-5 z-10 flex h-10 w-10 items-center justify-center rounded-full border border-slate-300 bg-[rgba(248,250,252,0.94)] text-lg font-semibold text-ink shadow-sm"
          aria-label="Zamknij"
        >
          ×
        </button>
        <div className="pr-14">
          <h3 className="text-lg font-bold text-ink">{selectedVehicle.name}</h3>
        </div>

        <form onSubmit={onSubmit} className="mx-auto mt-5 w-full max-w-[19.5rem] space-y-4 sm:max-w-none">
          <div className="space-y-3.5 sm:grid sm:grid-cols-2 sm:gap-3.5 sm:space-y-0 [&>*]:min-w-0">
            <VehicleServiceField label="Termin przeglądu technicznego">
              <input
                type="date"
                value={editVehicleInspectionDueDate}
                onChange={(event) => setEditVehicleInspectionDueDate(event.target.value)}
                className="vehicle-service-input vehicle-service-date-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
              />
            </VehicleServiceField>

            <VehicleServiceField label="Szacowany obecny przebieg">
              <input
                type="text"
                readOnly
                value={formatMileageKm(selectedVehicle.estimatedCurrentOdometer)}
                className="vehicle-service-input h-9 rounded-2xl border border-slate-300 bg-slate-100 px-3.5 text-sm text-slate-600"
              />
            </VehicleServiceField>
          </div>

          <div className="space-y-3.5">
            <div className="space-y-3.5 sm:grid sm:grid-cols-2 sm:gap-3.5 sm:space-y-0 [&>*]:min-w-0">
              <VehicleServiceField label="Nast. termin wymiany oleju">
                <input
                  type="date"
                  value={editVehicleOilChangeDueDate}
                  onChange={(event) => setEditVehicleOilChangeDueDate(event.target.value)}
                  className="vehicle-service-input vehicle-service-date-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                />
              </VehicleServiceField>

              <VehicleServiceField label="Stan licznika z dnia wymiany">
                <input
                  type="number"
                  min="0"
                  step="0.1"
                  inputMode="decimal"
                  value={editVehicleOilChangeOdometer}
                  onChange={(event) => setEditVehicleOilChangeOdometer(event.target.value)}
                  className="vehicle-service-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                  placeholder="np. 182450"
                />
              </VehicleServiceField>
            </div>

            <div className="space-y-3.5 sm:grid sm:grid-cols-2 sm:gap-3.5 sm:space-y-0 [&>*]:min-w-0">
              <VehicleServiceField label="Co ile wymiana">
                <input
                  type="number"
                  min="0"
                  step="1"
                  inputMode="numeric"
                  value={editVehicleOilChangeIntervalKm}
                  onChange={(event) => setEditVehicleOilChangeIntervalKm(event.target.value)}
                  className="vehicle-service-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                  placeholder="np. 15000"
                />
              </VehicleServiceField>

              <VehicleServiceField label="Następna wymiana przy">
                <input
                  type="text"
                  readOnly
                  value={nextOilChangeAtMileage}
                  className="vehicle-service-input h-9 rounded-2xl border border-slate-300 bg-slate-100 px-3.5 text-sm text-slate-600"
                  placeholder="Wyliczy się automatycznie"
                />
              </VehicleServiceField>
            </div>
          </div>

          <div className="space-y-3">
            <div className="text-center text-[10px] font-semibold uppercase tracking-[0.18em] text-steel">
              Daty wymiany opon
            </div>
            <div className="vehicle-service-tire-grid grid grid-cols-2 gap-2.5 [&>*]:min-w-0">
              <VehicleServiceField label="Obecna" className="vehicle-service-field--half" labelClassName="vehicle-service-field-label--half">
                <input
                  type="date"
                  value={editVehicleTireChangedAt}
                  onChange={(event) => setEditVehicleTireChangedAt(event.target.value)}
                  className="vehicle-service-input vehicle-service-date-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                />
              </VehicleServiceField>

              <VehicleServiceField label="Kolejna" className="vehicle-service-field--half" labelClassName="vehicle-service-field-label--half">
                <input
                  type="date"
                  value={editVehicleNextTireChangeDueDate}
                  onChange={(event) => setEditVehicleNextTireChangeDueDate(event.target.value)}
                  className="vehicle-service-input vehicle-service-date-input h-9 rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                />
              </VehicleServiceField>
            </div>
          </div>

          {userRole === "admin" ? (
            <>
              <div className="space-y-2.5">
                <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-steel">
                  IMEI
                </div>
                <input
                  list="vehicle-device-suggestions"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]{14,17}"
                  placeholder="Wybierz z listy lub wpisz ręcznie"
                  value={editDeviceImei}
                  onChange={(event) => {
                    const nextImei = event.target.value;
                    setEditDeviceImei(nextImei);

                    const matchedDevice = getDeviceByImei(nextImei);
                    if (!matchedDevice) {
                      setEditAssignedDeviceId("");
                      return;
                    }

                    setEditAssignedDeviceId(matchedDevice.id);
                    setEditDevicePhoneNumber((current) =>
                      current.trim() ? current : (matchedDevice.phone_number ?? ""),
                    );
                  }}
                  className="h-9 w-full rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                />
                <datalist id="vehicle-device-suggestions">
                  {systemDevices.map((device) => (
                    <option
                      key={device.id}
                      value={device.imei}
                      label={`${device.imei} · ${device.phone_number ?? "bez numeru"}`}
                    >
                      {device.imei} · {device.phone_number ?? "bez numeru"}
                    </option>
                  ))}
                </datalist>
                {editAssignedDeviceId ? (
                  <div className="text-[11px] text-steel">
                    Wybrane z bazy: {editDeviceImei}
                    {getDeviceById(editAssignedDeviceId)?.phone_number
                      ? ` · ${getDeviceById(editAssignedDeviceId)?.phone_number}`
                      : ""}
                  </div>
                ) : (
                  <div className="text-[11px] text-steel">
                    Ręczny wpis bez wyboru z bazy
                  </div>
                )}
              </div>

              <div className="grid grid-cols-1 gap-3.5 sm:grid-cols-2 [&>*]:min-w-0">
                <input
                  type="text"
                  placeholder="Nazwa pojazdu"
                  value={editVehicleName}
                  onChange={(event) => setEditVehicleName(event.target.value)}
                  className="h-9 w-full rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                  required
                />
                <input
                  type="text"
                  placeholder="Nr rej."
                  value={editVehiclePlateNumber}
                  onChange={(event) => setEditVehiclePlateNumber(event.target.value)}
                  className="h-9 w-full rounded-2xl border border-slate-300 bg-white px-3.5 text-sm"
                />
                <input
                  type="text"
                  placeholder="Telefon"
                  value={editDevicePhoneNumber}
                  onChange={(event) => setEditDevicePhoneNumber(event.target.value)}
                  className="h-9 w-full rounded-2xl border border-slate-300 bg-white px-3.5 text-sm sm:col-span-2"
                />
              </div>

              <div className="grid grid-cols-2 gap-3.5">
                <button
                  type="button"
                  onClick={() => setEditVehicleKind("passenger")}
                  className={`h-9 rounded-2xl border text-sm font-semibold transition ${
                    editVehicleKind === "passenger"
                      ? "border-slate-900 bg-slate-900 text-white"
                      : "border-slate-300 bg-white text-ink"
                  }`}
                >
                  Osobowe
                </button>
                <button
                  type="button"
                  onClick={() => setEditVehicleKind("delivery")}
                  className={`h-9 rounded-2xl border text-sm font-semibold transition ${
                    editVehicleKind === "delivery"
                      ? "border-slate-900 bg-slate-900 text-white"
                      : "border-slate-300 bg-white text-ink"
                  }`}
                >
                  Dostawcze
                </button>
              </div>

              <div className="flex items-center gap-3 rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2">
                <div className="text-[10px] font-semibold uppercase tracking-[0.22em] text-steel">
                  Podgląd
                </div>
                <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-white shadow-sm">
                  <svg viewBox="0 0 88 172" className="h-7 w-4" aria-hidden="true">
                    <g fill="none" fillRule="evenodd">
                      <path d="M18 9c7-6 45-6 52 0 9 9 12 27 13 76 1 48-4 71-13 79-7 6-45 6-52 0C9 156 4 133 5 85 6 36 9 18 18 9Z" fill={shiftHex(previewVehicleColor, -36)} />
                      <path d="M22 14c6-5 38-5 44 0 8 8 10 24 11 71 1 44-3 65-11 72-6 5-38 5-44 0-8-7-12-28-11-72 1-47 3-63 11-71Z" fill={shiftHex(previewVehicleColor, 8)} />
                      <path d="M27 19h34c8 0 14 6 16 19l2 12H9l2-12c2-13 8-19 16-19Z" fill="#102F45" />
                      <path d="M9 122h70l-2 13c-2 13-8 19-16 19H27c-8 0-14-6-16-19l-2-13Z" fill="#102F45" />
                      <path d="M13 45h11v37H13zM13 85h11v37H13zM64 45h11v37H64zM64 85h11v37H64z" fill="#0C2433" />
                      <path d="M18 9c7-6 45-6 52 0" stroke="#2F2F2F" strokeWidth="5" strokeLinecap="round" />
                      <path d="M5 84c0-46 4-67 13-75M83 84c0-46-4-67-13-75" stroke="#2F2F2F" strokeWidth="5" strokeLinecap="round" />
                      <path d="M18 164c7 6 45 6 52 0" stroke="#2F2F2F" strokeWidth="5" strokeLinecap="round" />
                      <path d="M6 40H1M87 40h-5" stroke="#2F2F2F" strokeWidth="5" strokeLinecap="round" />
                      <path d="M26 25h36c7 0 12 5 13 15l1 6H12l1-6c1-10 6-15 13-15Z" fill="#0C2433" />
                      <path d="M13 128h62l-1 6c-1 10-6 15-13 15H27c-7 0-12-5-13-15l-1-6Z" fill="#0C2433" />
                    </g>
                  </svg>
                </div>
              </div>

              <div className="flex flex-wrap gap-1.5">
                {VEHICLE_COLOR_OPTIONS.map((option) => (
                  <button
                    key={option.key}
                    type="button"
                    onClick={() => setEditVehicleColorKey(option.key)}
                    className={`h-5 w-5 rounded-full border-2 transition ${
                      editVehicleColorKey === option.key ? "scale-110 border-slate-950 shadow-md" : "border-white/80 shadow-sm"
                    }`}
                    style={{ backgroundColor: option.hex }}
                    aria-label={option.label}
                    title={option.label}
                  />
                ))}
              </div>
            </>
          ) : null}

          <div className="vehicle-edit-modal-actions grid gap-2 sm:grid-cols-[1fr_auto]">
            <button
              type="submit"
              className="rounded-2xl bg-ink px-4 py-2 text-sm font-semibold text-white"
            >
              {userRole === "admin" ? "Zapisz zmiany" : "Zapisz termin"}
            </button>
            {userRole === "admin" ? (
              <button
                type="button"
                onClick={onDeleteVehicle}
                className="rounded-2xl bg-coral px-4 py-2 text-sm font-semibold text-white"
              >
                Usuń auto
              </button>
            ) : null}
          </div>
        </form>
      </div>
    </div>
  ), overlayRoot);
}
