import type { Metadata } from "next";
import { listAllCategoriesForAdmin } from "@/lib/quotes/queries";
import { listAllRoomsForAdmin } from "@/lib/rooms/queries";
import { listBotSchedules, listRecentBotJobLogs } from "@/lib/admin/bot-queries";
import {
  createBotSchedule,
  toggleBotScheduleActive,
  deleteBotSchedule,
  updateBotScheduleTime,
  updateGeminiApiKeyAction,
  clearGeminiApiKeyAction,
} from "@/lib/admin/bot-actions";
import { getSiteSettings } from "@/lib/settings/site-settings";

export const metadata: Metadata = {
  title: "İçerik Botu",
};

const DAYS = [
  { value: "1", label: "Pzt" },
  { value: "2", label: "Sal" },
  { value: "3", label: "Çar" },
  { value: "4", label: "Per" },
  { value: "5", label: "Cum" },
  { value: "6", label: "Cmt" },
  { value: "0", label: "Paz" },
];

const TASK_LABELS: Record<string, string> = {
  CONFESSION: "İtiraf",
  QUOTE: "Güzel Söz",
  ROOM_ARTICLE: "Oda Makalesi",
  QUOTE_DAILY_ROTATION: "Günlük Söz Aktivasyonu (Tüm Kategoriler)",
};

function formatDays(runDays: string) {
  const set = new Set(runDays.split(","));
  return DAYS.filter((d) => set.has(d.value))
    .map((d) => d.label)
    .join(", ");
}

export default async function AdminBotPage() {
  const [categories, rooms, schedules, jobLogs, settings] = await Promise.all([
    listAllCategoriesForAdmin(),
    listAllRoomsForAdmin(),
    listBotSchedules(),
    listRecentBotJobLogs(),
    getSiteSettings(),
  ]);

  const maskedKey = settings.geminiApiKey ? `••••••••${settings.geminiApiKey.slice(-4)}` : null;

  return (
    <div className="p-8">
      <div className="mb-6 border-b border-border pb-6">
        <h1 className="text-[22px]">İçerik Botu</h1>
        <p className="mt-0.5 text-[12.5px] text-text-muted">
          Gemini API ile belirlediğiniz gün ve saatlerde otomatik itiraf, güzel söz ve oda tanıtım yazısı üretilir.
        </p>
      </div>

      <section className="mb-8">
        <h2 className="mb-3 text-[15px] font-bold">Gemini API Anahtarı</h2>
        <div className="max-w-xl rounded-2xl border border-border bg-surface p-4">
          <p className="mb-3 text-[12.5px] text-text-muted">
            {maskedKey ? (
              <>
                ✅ Anahtar tanımlı (<span className="font-mono">{maskedKey}</span>). Değiştirmek için aşağıya yenisini
                girip kaydedin.
              </>
            ) : (
              <>
                Henüz bir anahtar girilmedi — bu durumda bot-worker, servis üzerindeki{" "}
                <span className="font-mono">.env.local</span> dosyasındaki yedek anahtarı kullanır (varsa).
              </>
            )}{" "}
            Anahtarı{" "}
            <span className="font-mono">aistudio.google.com/apikey</span> adresinden alabilirsiniz.
          </p>
          <form action={updateGeminiApiKeyAction} className="flex flex-wrap gap-2">
            <input
              type="password"
              name="geminiApiKey"
              placeholder="Yeni Gemini API anahtarı"
              autoComplete="off"
              className="min-w-[220px] flex-1 rounded-lg border border-border px-3 py-2 text-[13px]"
            />
            <button type="submit" className="rounded-lg bg-accent px-4 py-2 text-[12.5px] font-semibold text-white">
              Kaydet
            </button>
          </form>
          {maskedKey && (
            <form action={clearGeminiApiKeyAction} className="mt-2">
              <button type="submit" className="text-[11.5px] font-semibold text-text-muted hover:text-accent">
                Anahtarı kaldır
              </button>
            </form>
          )}
        </div>
      </section>

      <div className="grid grid-cols-1 gap-8 lg:grid-cols-[380px_minmax(0,1fr)]">
        <section>
          <h2 className="mb-3 text-[15px] font-bold">Yeni Zamanlama</h2>
          <form action={createBotSchedule} className="flex flex-col gap-3 rounded-2xl border border-border bg-surface p-4">
            <div>
              <label className="mb-1 block text-[12px] font-semibold text-text-muted">Görev Tipi</label>
              <select name="taskType" required className="w-full rounded-lg border border-border px-3 py-2 text-[13px]">
                <option value="CONFESSION">İtiraf</option>
                <option value="QUOTE">Güzel Söz (Gemini ile üretir)</option>
                <option value="ROOM_ARTICLE">Oda Makalesi</option>
                <option value="QUOTE_DAILY_ROTATION">Günlük Söz Aktivasyonu (bekleyen havuzdan, tüm kategoriler)</option>
              </select>
              <p className="mt-1 text-[11px] text-text-muted">
                &quot;Günlük Söz Aktivasyonu&quot; Gemini çağırmaz — her aktif kategorideki en eski bekleyen sözü otomatik
                yayına alır. Günde birden fazla kez çalıştırmak için aynı görevi farklı saatlerle birden fazla kez
                ekleyebilirsiniz.
              </p>
            </div>

            <div>
              <label className="mb-1 block text-[12px] font-semibold text-text-muted">Güzel Söz için Kategori</label>
              <select name="categoryId" className="w-full rounded-lg border border-border px-3 py-2 text-[13px]">
                <option value="">— Seçiniz —</option>
                {categories.map((category) => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="mb-1 block text-[12px] font-semibold text-text-muted">Oda Makalesi için Oda</label>
              <select name="roomId" className="w-full rounded-lg border border-border px-3 py-2 text-[13px]">
                <option value="">— Seçiniz —</option>
                {rooms.map((room) => (
                  <option key={room.id} value={room.id}>
                    {room.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="mb-1 block text-[12px] font-semibold text-text-muted">Günler</label>
              <div className="flex flex-wrap gap-2">
                {DAYS.map((day) => (
                  <label
                    key={day.value}
                    className="flex items-center gap-1.5 rounded-lg border border-border px-2.5 py-1.5 text-[12px] font-semibold text-text-muted"
                  >
                    <input type="checkbox" name="runDays" value={day.value} defaultChecked className="accent-accent" />
                    {day.label}
                  </label>
                ))}
              </div>
            </div>

            <div>
              <label className="mb-1 block text-[12px] font-semibold text-text-muted">Saat</label>
              <input
                type="time"
                name="runTime"
                required
                defaultValue="09:00"
                className="w-full rounded-lg border border-border px-3 py-2 text-[13px]"
              />
            </div>

            <label className="flex items-center gap-2 text-[12px] text-text-muted">
              <input type="checkbox" name="autoPublish" className="accent-accent" />
              Üretilen içeriği otomatik yayınla (işaretlenmezse pasif olarak eklenir, admin onaylar)
            </label>

            <button type="submit" className="self-start rounded-lg bg-accent px-4 py-2 text-[12.5px] font-semibold text-white">
              Zamanlama Ekle
            </button>
          </form>
        </section>

        <section className="flex flex-col gap-8">
          <div>
            <h2 className="mb-3 text-[15px] font-bold">Zamanlamalar</h2>
            {schedules.length === 0 ? (
              <p className="text-[13px] text-text-muted">Henüz zamanlama eklenmedi.</p>
            ) : (
              <div className="flex flex-col gap-2">
                {schedules.map((schedule) => {
                  const toggle = toggleBotScheduleActive.bind(null, schedule.id);
                  const remove = deleteBotSchedule.bind(null, schedule.id);
                  const updateTime = updateBotScheduleTime.bind(null, schedule.id);
                  const target = schedule.category?.name ?? schedule.room?.name;
                  const scheduleDays = new Set(schedule.runDays.split(","));
                  return (
                    <div key={schedule.id} className="rounded-xl border border-border bg-surface px-3 py-2.5">
                      <div className="flex items-center justify-between">
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <span className="text-[13.5px] font-semibold">{TASK_LABELS[schedule.taskType]}</span>
                            {target && <span className="text-[12px] text-text-muted">({target})</span>}
                            <span
                              className={`rounded-full px-2 py-0.5 text-[10.5px] font-semibold ${
                                schedule.isActive ? "bg-green-100 text-green-700" : "bg-accent/10 text-accent"
                              }`}
                            >
                              {schedule.isActive ? "Aktif" : "Pasif"}
                            </span>
                            {schedule.autoPublish && (
                              <span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10.5px] font-semibold text-blue-700">
                                Otomatik Yayın
                              </span>
                            )}
                          </div>
                          <p className="text-[12px] text-text-muted">
                            {formatDays(schedule.runDays)} — {schedule.runTime}
                            {schedule.lastRunAt && <> · son çalışma: {schedule.lastRunAt.toLocaleString("tr-TR")}</>}
                          </p>
                        </div>
                        <div className="ml-3 flex shrink-0 gap-1.5">
                          <form action={toggle}>
                            <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-text-muted hover:bg-bg-alt">
                              {schedule.isActive ? "Durdur" : "Başlat"}
                            </button>
                          </form>
                          <form action={remove}>
                            <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-accent hover:bg-accent/10">
                              Sil
                            </button>
                          </form>
                        </div>
                      </div>

                      <details className="group mt-2 border-t border-dashed border-border pt-2">
                        <summary className="cursor-pointer text-[11.5px] font-semibold text-accent">
                          Zamanlamayı Düzenle
                        </summary>
                        <form action={updateTime} className="mt-2 flex flex-col gap-2">
                          <div className="flex flex-wrap gap-1.5">
                            {DAYS.map((day) => (
                              <label
                                key={day.value}
                                className="flex items-center gap-1 rounded-lg border border-border px-2 py-1 text-[11px] font-semibold text-text-muted"
                              >
                                <input
                                  type="checkbox"
                                  name="runDays"
                                  value={day.value}
                                  defaultChecked={scheduleDays.has(day.value)}
                                  className="accent-accent"
                                />
                                {day.label}
                              </label>
                            ))}
                          </div>
                          <div className="flex items-center gap-2">
                            <input
                              type="time"
                              name="runTime"
                              required
                              defaultValue={schedule.runTime}
                              className="rounded-lg border border-border px-2.5 py-1.5 text-[12.5px]"
                            />
                            <button
                              type="submit"
                              className="rounded-lg bg-accent px-3 py-1.5 text-[11.5px] font-semibold text-white hover:bg-accent-dark"
                            >
                              Kaydet
                            </button>
                          </div>
                        </form>
                      </details>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          <div>
            <h2 className="mb-3 text-[15px] font-bold">Son Çalışmalar</h2>
            {jobLogs.length === 0 ? (
              <p className="text-[13px] text-text-muted">Henüz bir çalışma kaydı yok.</p>
            ) : (
              <div className="flex flex-col gap-1.5">
                {jobLogs.map((log) => (
                  <div key={log.id} className="flex items-center justify-between rounded-xl border border-border bg-surface px-3 py-2.5">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-[13px] font-semibold">{TASK_LABELS[log.schedule.taskType]}</span>
                        <span
                          className={`rounded-full px-2 py-0.5 text-[10.5px] font-semibold ${
                            log.status === "SUCCESS" ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
                          }`}
                        >
                          {log.status === "SUCCESS" ? "Başarılı" : "Başarısız"}
                        </span>
                      </div>
                      {log.errorMessage && <p className="truncate text-[12px] text-red-600">{log.errorMessage}</p>}
                    </div>
                    <span className="ml-3 shrink-0 text-[11.5px] text-text-muted">{log.runAt.toLocaleString("tr-TR")}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
