"use client";

import { useEffect, useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useItem, useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import {
  Button,
  Card,
  Field,
  Input,
  PageHeader,
  Select,
  Spinner,
  Switch,
} from "@/components/ui";
import { toFa } from "@/lib/utils";

interface Scene {
  id: number;
  name: string;
}

interface SceneSettings {
  active_scene_id?: number | string | null;
  scene_volume?: number | string | null;
  background_play_seconds?: number | string | null;
  video_enabled?: boolean;
}

export default function SceneSettingsPage() {
  const { data, loading } = useItem<SceneSettings>("/scene-settings");
  const { data: scenes } = useList<Scene>("/scenes");
  const toast = useToast();

  const [activeSceneId, setActiveSceneId] = useState("");
  const [sceneVolume, setSceneVolume] = useState("");
  const [backgroundPlaySeconds, setBackgroundPlaySeconds] = useState("");
  const [videoEnabled, setVideoEnabled] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!data) return;
    setActiveSceneId(
      data.active_scene_id != null ? String(data.active_scene_id) : "",
    );
    setSceneVolume(data.scene_volume != null ? String(data.scene_volume) : "");
    setBackgroundPlaySeconds(
      data.background_play_seconds != null
        ? String(data.background_play_seconds)
        : "",
    );
    setVideoEnabled(!!data.video_enabled);
  }, [data]);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      await apiFetch("/scene-settings", {
        method: "PUT",
        body: {
          active_scene_id: activeSceneId ? Number(activeSceneId) : null,
          scene_volume: sceneVolume ? Number(sceneVolume) : null,
          background_play_seconds: backgroundPlaySeconds
            ? Number(backgroundPlaySeconds)
            : null,
          video_enabled: videoEnabled,
        },
      });
      toast.success("تنظیمات صحنه ذخیره شد.");
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div>
      <PageHeader
        title="تنظیمات صحنه"
        subtitle="پیکربندی صحنه فعال، صدا و پخش پس‌زمینه"
      />

      {loading ? (
        <div className="flex justify-center py-16">
          <Spinner />
        </div>
      ) : (
        <Card className="max-w-xl">
          <form onSubmit={save} className="flex flex-col gap-4">
            <Field label="صحنه فعال">
              <Select
                value={activeSceneId}
                onChange={(e) => setActiveSceneId(e.target.value)}
              >
                <option value="">انتخاب صحنه</option>
                {scenes.map((s) => (
                  <option key={s.id} value={String(s.id)}>
                    {s.name} ({toFa(s.id)})
                  </option>
                ))}
              </Select>
            </Field>

            <Field label="میزان صدای صحنه">
              <Input
                type="number"
                value={sceneVolume}
                onChange={(e) => setSceneVolume(e.target.value)}
                placeholder="0"
                dir="ltr"
              />
            </Field>

            <Field label="مدت پخش پس‌زمینه (ثانیه)">
              <Input
                type="number"
                value={backgroundPlaySeconds}
                onChange={(e) => setBackgroundPlaySeconds(e.target.value)}
                placeholder="0"
                dir="ltr"
              />
            </Field>

            <Switch
              checked={videoEnabled}
              onChange={setVideoEnabled}
              label="نمایش ویدیو فعال باشد"
            />

            <div className="flex justify-end pt-2">
              <Button type="submit" loading={saving}>
                ذخیره تنظیمات
              </Button>
            </div>
          </form>
        </Card>
      )}
    </div>
  );
}
