import React, { useState } from "react";
import type { ClientSite, DashboardState, Incident } from "../types";
import { api } from "../api";
function IncidentRow({
  incident,
  onRefresh,
}: {
  incident: Incident;
  onRefresh: () => Promise<void>;
}) {
  const [notes, setNotes] = useState(incident.notes),
    [editing, setEditing] = useState(false),
    [busy, setBusy] = useState(false),
    [error, setError] = useState("");
  const minutes = Math.max(
    0,
    Math.round(
      (Date.parse(incident.resolvedAt || new Date().toISOString()) -
        Date.parse(incident.openedAt)) /
        60000,
    ),
  );
  async function save() {
    setBusy(true);
    try {
      await api(`/api/incidents/${incident.id}`, {
        method: "PUT",
        body: JSON.stringify({ notes }),
      });
      setEditing(false);
      await onRefresh();
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <div className="py-3 border-t border-slate-800 text-sm">
      <div className="flex flex-wrap justify-between gap-2">
        <strong>{incident.siteName}</strong>
        <span
          className={incident.resolvedAt ? "text-emerald-300" : "text-red-300"}
        >
          {incident.resolvedAt ? "Pulih" : "Aktif"} · {minutes} minit sejak
          kegagalan pertama direkodkan
        </span>
      </div>
      <p className="text-xs text-slate-400 mt-1">
        {new Date(incident.openedAt).toLocaleString("ms-MY", {
          timeZone: "Asia/Kuala_Lumpur",
        })}{" "}
        · {incident.errorMessage}
      </p>
      {!editing && incident.notes && (
        <p className="mt-2 whitespace-pre-line">{incident.notes}</p>
      )}
      {editing ? (
        <div className="mt-2 space-y-2">
          <textarea
            aria-label="Nota tindakan"
            value={notes}
            maxLength={4000}
            onChange={(e) => setNotes(e.target.value)}
            className="w-full p-2 bg-slate-800 rounded-lg border border-slate-700"
          />
          <button disabled={busy} onClick={save} className="text-blue-300">
            {busy ? "Menyimpan..." : "Simpan nota"}
          </button>
          {error && <p className="text-red-300">{error}</p>}
        </div>
      ) : (
        <button
          onClick={() => {
            setNotes(incident.notes);
            setEditing(true);
          }}
          className="text-blue-300 text-xs mt-2"
        >
          Catat tindakan
        </button>
      )}
    </div>
  );
}
export function OperationsPanel({
  state,
  onRefresh,
  onEdit,
}: {
  state: DashboardState;
  onRefresh: () => Promise<void>;
  onEdit: (s: ClientSite) => void;
}) {
  const [showPassword, setShowPassword] = useState(false),
    [currentPassword, setCurrentPassword] = useState(""),
    [newPassword, setNewPassword] = useState(""),
    [error, setError] = useState(""),
    [busy, setBusy] = useState(false);
  const today = new Date().toLocaleDateString("en-CA", {
    timeZone: "Asia/Kuala_Lumpur",
  });
  const renewals = state.sites
    .flatMap((site) =>
      (
        [
          ["Domain", site.domainRenewalDate],
          ["Hosting", site.hostingRenewalDate],
        ] as const
      )
        .filter(([, date]) => date)
        .map(([type, date]) => ({
          site,
          type,
          date: date!,
          days: Math.round((Date.parse(date!) - Date.parse(today)) / 86400000),
        })),
    )
    .filter((r) => r.days <= 30)
    .sort((a, b) => a.days - b.days);
  async function changePassword(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      await api("/api/auth/password", {
        method: "POST",
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      setCurrentPassword("");
      setNewPassword("");
      location.reload();
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <div className="space-y-4">
      {renewals.length > 0 && (
        <section className="bg-slate-900 border border-amber-800/60 rounded-xl p-4">
          <h2 className="font-semibold text-amber-200 mb-2">
            Renewal dalam 30 hari / sudah lepas tarikh
          </h2>
          <div className="space-y-2 max-h-40 overflow-auto">
            {renewals.map((r) => (
              <button
                key={r.site.id + r.type}
                onClick={() => onEdit(r.site)}
                className="flex flex-wrap justify-between w-full text-left gap-2 text-sm"
              >
                <span>
                  {r.site.name} · {r.type}
                </span>
                <span
                  className={r.days < 0 ? "text-red-300" : "text-amber-300"}
                >
                  {r.date} ·{" "}
                  {r.days < 0
                    ? `${-r.days} hari lepas tarikh`
                    : r.days === 0
                      ? "Hari ini"
                      : `${r.days} hari lagi`}
                </span>
              </button>
            ))}
          </div>
        </section>
      )}
      {state.incidents.length > 0 && (
        <details className="bg-slate-900 border border-slate-800 rounded-xl p-4">
          <summary className="cursor-pointer font-semibold">
            Insiden & rekod tindakan (
            {state.incidents.filter((i) => !i.resolvedAt).length} aktif)
          </summary>
          <div className="max-h-96 overflow-auto mt-3">
            {state.incidents.slice(0, 30).map((i) => (
              <IncidentRow key={i.id} incident={i} onRefresh={onRefresh} />
            ))}
          </div>
        </details>
      )}
      <div className="flex flex-wrap justify-between text-xs text-slate-500 gap-2">
        <span>
          Retensi semakan: {state.monitor.retentionDays} hari · Waktu Malaysia
        </span>
        <button
          className="text-blue-300"
          onClick={() => setShowPassword(!showPassword)}
        >
          Tukar kata laluan
        </button>
      </div>
      {showPassword && (
        <form
          onSubmit={changePassword}
          className="bg-slate-900 border border-slate-700 rounded-xl p-4 space-y-3 max-w-lg"
        >
          <h2 className="font-semibold">Tukar kata laluan admin</h2>
          <label className="block text-sm">
            Kata laluan semasa
            <input
              required
              type="password"
              autoComplete="current-password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              className="block w-full p-2 mt-1 bg-slate-800 rounded-lg"
            />
          </label>
          <label className="block text-sm">
            Kata laluan baharu (12+ aksara)
            <input
              required
              minLength={12}
              type="password"
              autoComplete="new-password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="block w-full p-2 mt-1 bg-slate-800 rounded-lg"
            />
          </label>
          {error && (
            <p role="alert" className="text-red-300 text-sm">
              {error}
            </p>
          )}
          <button
            disabled={busy}
            className="px-4 py-2 bg-blue-600 rounded-lg text-sm disabled:opacity-50"
          >
            {busy ? "Menyimpan..." : "Simpan & log keluar"}
          </button>
        </form>
      )}
    </div>
  );
}
