import { useState } from "react";
import { clinicianApi } from "../../api/client";
import { sameHours, timeZones } from "../../logic/hours";
import { Button, Callout, Field, Icon, Notice, Panel, Select } from "../kit";
import { useClinician } from "../session";
import { errorText } from "../ui";
import { SaveRow } from "./bits";
import { HoursEditor } from "./HoursEditor";

/** YCI-5: the clinic's time zone, opening hours and alert-watch hours. A new clinic has none, so nothing can ring until they are set. */
export function HoursSection({ onSaved }: { onSaved: (message: string) => void }) {
  const { clinic, setClinic } = useClinician();
  const [zone, setZone] = useState(clinic.timeZone);
  const [opening, setOpening] = useState({ hours: clinic.openingHours, valid: true });
  const [watch, setWatch] = useState({ hours: clinic.alertWatchHours, valid: true });
  // Copying the opening hours redraws the alert-watch rows from them.
  const [watchDraw, setWatchDraw] = useState(0);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  const owner = clinic.role === "owner";
  const missing = [!opening.hours.length && "opening hours", !watch.hours.length && "alert-watch hours"].filter(Boolean);

  const save = async () => {
    if (!opening.valid || !watch.valid) return setError("Fix the times marked above first.");
    setSaving(true);
    try {
      const saved = await clinicianApi.updateClinic(
        {
          ...(zone === clinic.timeZone ? {} : { timeZone: zone }),
          ...(sameHours(opening.hours, clinic.openingHours) ? {} : { openingHours: opening.hours }),
          ...(sameHours(watch.hours, clinic.alertWatchHours) ? {} : { alertWatchHours: watch.hours }),
        },
        clinic,
      );
      setClinic(saved);
      setError("");
      onSaved("Clinic hours saved.");
    } catch (e) {
      setError(errorText(e));
    } finally {
      setSaving(false);
    }
  };
  const copyOpening = () => {
    setWatch({ hours: opening.hours, valid: opening.valid });
    setWatchDraw((n) => n + 1);
  };

  return (
    <>
      <Notice id="ring-why" icon="phone-lock-line" title="Yasmar can only ring inside these hours.">
        A check-in rings while the clinic is open and someone watches for urgent alerts, in the clinic's time zone, and between 08:00 and 20:00
        where the patient is. Outside them it waits.
      </Notice>
      {missing.length > 0 && (
        <Callout tone="amber" role="status">
          No {missing.join(" or ")} yet, so Yasmar can't ring any patient. Set them below.
        </Callout>
      )}
      {!owner && <Callout icon="lock-line">Only the clinic's owner can change these hours.</Callout>}
      <Panel title="Clinic time zone" icon="global-line" iconClass="text-blue-icon">
        <Field id="clinic-zone" label="Time zone" className="max-w-[360px]">
          <Select id="clinic-zone" value={zone} disabled={!owner} aria-describedby="ring-why" onChange={(e) => setZone(e.target.value)}>
            {timeZones(zone).map((z) => (
              <option key={z} value={z}>
                {z.replace(/_/g, " ")}
              </option>
            ))}
          </Select>
        </Field>
      </Panel>
      <div className="grid gap-4 lg:grid-cols-2">
        <Panel title="Opening hours" icon="hospital-line" iconClass="text-green-icon">
          <HoursEditor id="opening" legend="Opening hours" help="When the clinic is open." hours={clinic.openingHours} disabled={!owner} onChange={(hours, valid) => setOpening({ hours, valid })} />
        </Panel>
        <Panel title="Someone watches for urgent alerts" icon="alarm-warning-line" iconClass="text-red-icon">
          <HoursEditor
            key={watchDraw}
            id="watch"
            legend="Someone watches for urgent alerts"
            help="When someone at the clinic can act on an urgent note within 15 minutes."
            hours={watch.hours}
            disabled={!owner}
            onChange={(hours, valid) => setWatch({ hours, valid })}
          />
          {owner && (
            <Button size="sm" className="self-start" onClick={copyOpening}>
              <Icon name="file-copy-line" size={14} /> Same as opening hours
            </Button>
          )}
        </Panel>
      </div>
      <SaveRow error={error} busy={saving} disabled={!owner} onSave={() => void save()} label="Save hours" />
    </>
  );
}
