import { subdomainInfo } from "../orchestrator"
import { Form, useAction, type LoaderProps } from "@workshop/nano-remix"
import kv, { type CronJobHistory } from "@workshop/shared/kv"
import { zone } from "@workshop/shared/utils"
import { useMemo } from "hono/jsx"
import { DateTime } from "luxon"

export const loader = async (_req: Request) => {
  const info = await subdomainInfo()
  const cronJobs = await kv.get("cronJobs", {})
  return { subdomains: info.map((i) => i.name), cronJobs }
}

export const action = async () => {
  await kv.remove("cronJobs")
  return { success: true }
}

export default function Index({ subdomains, cronJobs }: LoaderProps<typeof loader>) {
  const actionResult = useAction<typeof action>()
  const url = new URL(import.meta.url)

  const sortedEntries = useMemo(() => {
    return Object.entries(cronJobs).sort((a, b) => {
      const aHistory = a[1] ?? []
      const bHistory = b[1] ?? []
      const latestA = aHistory[0]
      const latestB = bHistory[0]
      if (!latestA && !latestB) return 0
      if (!latestA) return 1
      if (!latestB) return -1
      return DateTime.fromISO(latestB.runAt).diff(DateTime.fromISO(latestA.runAt)).as("milliseconds")
    })
  }, [cronJobs])

  return (
    <div>
      <h2>Subdomain Servers</h2>
      <ul>
        {subdomains.map((subdomain) => (
          <li key={subdomain}>
            <a href={`${url.protocol}//${subdomain}.${url.host}`}>{subdomain}</a>
          </li>
        ))}
      </ul>
      <h2>CronJobs (Only showing the last 5 runs)</h2>
      <Form name="clearCronJobs">
        <button type="submit" disabled={actionResult.loading}>
          Erase Cron Jobs Logs
        </button>
        {actionResult.data?.success && <p style={{ color: "green" }}>Cron jobs successfully erased!</p>}
        {actionResult.error && <p style={{ color: "red" }}>Error clearing cron jobs: {actionResult.error}</p>}
      </Form>

      <ul>
        {sortedEntries.map(([id, history]) => (
          <li key={id}>
            <h4>{id}</h4>
            <JobHistory history={history} />
          </li>
        ))}
      </ul>
    </div>
  )
}

const JobHistory = ({ history }: { history: CronJobHistory[] }) => {
  return (
    <ul>
      {history.map((run, index) => (
        <li key={index}>
          <strong>{DateTime.fromISO(run.runAt).setZone(zone).toRFC2822()}</strong>
          {run.error && <div style={{ color: "red" }}>Error: {run.error}</div>}
          {run.stdout && <pre>Output: {run.stdout}</pre>}
          {run.stderr && <pre style={{ color: "red" }}>Error Output: {run.stderr}</pre>}
        </li>
      ))}
    </ul>
  )
}
