import { CalendarDays, Download, Play } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useConfigStore } from "@/stores/configStore";
import { apiJson } from "@/utils/api";
import type { RecordingItem } from "@/types/api";

function toLocalDateInputValue(d: Date) {
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

export default function Playback() {
  const { config, isLoading, error, load } = useConfigStore();
  const dateInputRef = useRef<HTMLInputElement | null>(null);
  const [camera, setCamera] = useState<string>("");
  const [date, setDate] = useState<string>(() => toLocalDateInputValue(new Date()));
  const [items, setItems] = useState<RecordingItem[]>([]);
  const [selected, setSelected] = useState<RecordingItem | null>(null);
  const [listError, setListError] = useState<string | null>(null);
  const [listLoading, setListLoading] = useState(false);

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

  useEffect(() => {
    const first = config?.cameras?.[0]?.name;
    if (first && !camera) setCamera(first);
  }, [config?.cameras, camera]);

  const canQuery = useMemo(() => Boolean(camera), [camera]);

  const openDatePicker = () => {
    const input = dateInputRef.current;
    if (!input) return;
    const pickerInput = input as HTMLInputElement & { showPicker?: () => void };
    if (pickerInput.showPicker) {
      pickerInput.showPicker();
      return;
    }
    input.focus();
    input.click();
  };

  useEffect(() => {
    let alive = true;
    const run = async () => {
      if (!canQuery) return;
      setListLoading(true);
      setListError(null);
      try {
        const q = new URLSearchParams();
        q.set("camera", camera);
        if (date) q.set("date", date);
        const res = await apiJson<RecordingItem[]>(`/recordings?${q.toString()}`, {
          method: "GET",
        });
        if (!alive) return;
        setItems(res);
        setSelected((prev) => {
          if (prev && res.some((x) => x.filename === prev.filename)) return prev;
          return res[0] ?? null;
        });
      } catch (e) {
        if (!alive) return;
        setItems([]);
        setSelected(null);
        if (typeof e === "object" && e && "status" in e) {
          setListError(`http_${(e as { status: number }).status}`);
        } else {
          setListError("failed_to_load_recordings");
        }
      } finally {
        if (alive) setListLoading(false);
      }
    };
    void run();
    return () => {
      alive = false;
    };
  }, [camera, date, canQuery]);

  return (
    <div className="space-y-4">
      <div>
        <div className="text-sm font-semibold">Playback</div>
        <div className="text-xs text-zinc-400">Chọn camera + ngày, phát file fMP4</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}

      <div className="grid gap-3 lg:grid-cols-[320px_1fr]">
        <div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-3">
          <div className="space-y-3">
            <div>
              <label className="text-xs text-zinc-400">Camera</label>
              <select
                value={camera}
                onChange={(e) => setCamera(e.target.value)}
                disabled={isLoading && !config}
                className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
              >
                {(config?.cameras ?? []).map((c) => (
                  <option key={c.name} value={c.name}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="text-xs text-zinc-400">Date</label>
              <div className="mt-1 flex items-center gap-2">
                <input
                  ref={dateInputRef}
                  type="date"
                  value={date}
                  onChange={(e) => setDate(e.target.value)}
                  className="h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
                />
                <button
                  type="button"
                  onClick={openDatePicker}
                  className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
                  title="Open calendar"
                >
                  <CalendarDays className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>

          <div className="mt-4 border-t border-zinc-800 pt-3">
            <div className="flex items-center justify-between">
              <div className="text-xs font-medium text-zinc-200">Files</div>
              <div className="text-xs text-zinc-400">
                {listLoading ? "loading" : `${items.length}`}
              </div>
            </div>
            {listError ? (
              <div className="mt-2 text-xs text-rose-300">{listError}</div>
            ) : null}

            <div className="mt-2 max-h-[420px] space-y-1 overflow-auto pr-1">
              {items.map((it) => {
                const dt = new Date(it.timestamp);
                const t = dt.toLocaleTimeString();
                const active = selected?.filename === it.filename;
                return (
                  <div
                    key={it.filename}
                    className={[
                      "flex items-center justify-between gap-2 rounded-md border px-2 py-2",
                      active
                        ? "border-zinc-700 bg-zinc-950/40"
                        : "border-zinc-800 bg-zinc-950/10 hover:bg-zinc-950/30",
                    ].join(" ")}
                  >
                    <div className="min-w-0">
                      <div className="truncate text-xs text-zinc-100">{t}</div>
                      <div className="truncate text-[11px] text-zinc-500">{it.filename}</div>
                    </div>

                    <div className="flex shrink-0 items-center gap-1">
                      <button
                        type="button"
                        onClick={() => setSelected(it)}
                        className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
                        title="Play"
                      >
                        <Play className="h-4 w-4" />
                      </button>
                      <a
                        href={it.url}
                        download
                        className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
                        title="Download"
                      >
                        <Download className="h-4 w-4" />
                      </a>
                    </div>
                  </div>
                );
              })}
              {!listLoading && items.length === 0 ? (
                <div className="rounded-md border border-zinc-800 bg-zinc-950/10 px-3 py-2 text-xs text-zinc-400">
                  Không có file.
                </div>
              ) : null}
            </div>
          </div>
        </div>

        <div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-3">
          <div className="text-xs font-medium text-zinc-200">Player</div>
          <div className="mt-2 aspect-video w-full overflow-hidden rounded-md border border-zinc-800 bg-black">
            {selected ? (
              <video
                key={selected.filename}
                className="h-full w-full"
                controls
                playsInline
                src={selected.url}
              />
            ) : (
              <div className="flex h-full w-full items-center justify-center text-sm text-zinc-400">
                Chọn 1 file để phát
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

