import { useEffect, useMemo, useState } from "react";
import CameraTile from "@/components/CameraTile";
import { usePathsStatus } from "@/hooks/usePathsStatus";
import { useConfigStore } from "@/stores/configStore";
import { getMediamtxWebrtcBaseUrl } from "@/utils/api";

type Grid = 1 | 4 | 9;

export default function Live() {
  const { config, isLoading, error, load } = useConfigStore();
  const { readyByName } = usePathsStatus(5000);
  const [grid, setGrid] = useState<Grid>(4);

  useEffect(() => {
    if (!config) void load();
  }, [config, load]);

  const cams = useMemo(() => {
    const list = config?.cameras ?? [];
    return list.slice(0, grid);
  }, [config, grid]);

  const webrtcBaseUrl = useMemo(() => {
    return getMediamtxWebrtcBaseUrl(config?.mediamtx_webrtc_url);
  }, [config?.mediamtx_webrtc_url]);

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div>
          <div className="text-sm font-semibold">Live View</div>
          <div className="text-xs text-zinc-400">WebRTC grid (auto reconnect + lazy load)</div>
        </div>

        <div className="flex items-center gap-2">
          <label className="text-xs text-zinc-400">Grid</label>
          <select
            value={grid}
            onChange={(e) => setGrid(Number(e.target.value) as Grid)}
            className="h-9 rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
          >
            <option value={1}>1</option>
            <option value={4}>4</option>
            <option value={9}>9</option>
          </select>
        </div>
      </div>

      {error ? (
        <div className="rounded-lg border border-rose-900/60 bg-rose-950/30 px-4 py-3 text-sm text-rose-200">
          {error}
        </div>
      ) : null}

      {isLoading && !config ? (
        <div className="rounded-lg border border-zinc-800 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-300">
          Đang tải cấu hình...
        </div>
      ) : null}

      {config && config.cameras.length === 0 ? (
        <div className="rounded-lg border border-zinc-800 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-300">
          Chưa có camera. Thêm camera trong Settings.
        </div>
      ) : null}

      <div
        className={[
          "grid gap-3",
          grid === 1 ? "grid-cols-1" : "grid-cols-1 md:grid-cols-2",
          grid === 9 ? "lg:grid-cols-3" : "",
        ].join(" ")}
      >
        {cams.map((c) => (
          <CameraTile
            key={c.name}
            name={c.name}
            webrtcBaseUrl={webrtcBaseUrl}
            isOnline={readyByName.get(c.name) ?? false}
          />
        ))}
      </div>
    </div>
  );
}

