import React, { useEffect, useState } from "react";
import axios from "axios";
import { Button } from "@/prime-react";
import { Column } from "@/prime-react";
import { DataTable } from "@/prime-react";
import { Message } from "@/prime-react";
import { ProgressSpinner } from "@/prime-react";
import { Tag } from "@/prime-react";
import { TIMER_KIND, TIMER_KIND_CODE, TIMER_STATUS, TIMER_STATUS_CODE } from "@/shared/status";
import ChatflowFilters, { ALL, asParams, EMPTY_FILTERS } from "../shared/ChatflowFilters";

const STATUSES = [
    { label: "All statuses", value: ALL },
    { label: "Pending",      value: TIMER_STATUS.PENDING },
    { label: "Fired",        value: TIMER_STATUS.FIRED },
    { label: "Cancelled",    value: TIMER_STATUS.CANCELLED },
];

// `timer` stopped being only about flow chases: appointment reminders (18/08/2026), reschedule
// chases and slot holds all live in the same table, and reading them as one list is reading four
// unrelated things as one.
const KINDS = [
    { label: "All kinds",    value: ALL },
    { label: "Flow node",    value: TIMER_KIND.FLOW_NODE },
    { label: "Appointment",  value: TIMER_KIND.APPOINTMENT_REMINDER },
    { label: "Reschedule",   value: TIMER_KIND.RESCHEDULE_CHASE },
    { label: "Slot hold",    value: TIMER_KIND.SLOT_HOLD },
];

const kindSeverity = (k) => ({
    [TIMER_KIND.FLOW_NODE]:            "info",
    [TIMER_KIND.APPOINTMENT_REMINDER]: "success",
    [TIMER_KIND.RESCHEDULE_CHASE]:     "warning",
    [TIMER_KIND.SLOT_HOLD]:            "secondary",
}[k] || "info");

const statusSeverity = (s) => ({
    [TIMER_STATUS.PENDING]:   "warning",
    [TIMER_STATUS.FIRED]:     "success",
    [TIMER_STATUS.CANCELLED]: "secondary",
}[s] || "info");

const Timer = () => {
    const [items, setItems] = useState([]);
    const [organizations, setOrganizations] = useState([]);
    const [filters, setFilters] = useState(EMPTY_FILTERS);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const load = async (f = filters) => {
        setLoading(true);
        setError(null);
        try {
            const res = await axios.get("/timer/list", { params: asParams(f) });
            setItems(res.data?.timers || []);
            setOrganizations(res.data?.organizations || []);
        } catch (err) {
            console.error(err);
            setError(err.response?.data?.message || "Could not load timers.");
            setItems([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(); }, []);

    const apply = (f = filters) => { setFilters(f); load(f); };
    const clear = () => apply(EMPTY_FILTERS);

    const dateBody = (k) => (row) => row[k] ? new Date(row[k]).toLocaleString("en-HK") : "—";
    const orgBody = (row) => (
        row.organization_name
            ? <span>{row.organization_name} <span style={{ opacity: .55 }}>#{row.organization_id}</span></span>
            : <span style={{ opacity: .6 }}>#{row.organization_id} (deleted)</span>
    );
    // The two id sets are mutually exclusive (see App\Models\Timer): a flow timer names a run and a
    // node, an appointment timer names an appointment. Showing both columns for both leaves half
    // the table empty and says nothing.
    const targetBody = (row) => (
        row.kind === TIMER_KIND.APPOINTMENT_REMINDER
            ? <span>appointment #{row.appointment_id ?? "—"}</span>
            : (
                <div>
                    <code style={{ fontSize: 11 }}>{row.node_id || "—"}</code>
                    {row.flow_run_id ? <div style={{ fontSize: 10, opacity: .6 }}>run {row.flow_run_id}</div> : null}
                </div>
            )
    );

    return (
        <div className="pt-fade-in">
            <div className="pt-page-head">
                <div>
                    <h2>Reminder timers</h2>
                    <p>Every scheduled wake-up: flow chases, appointment reminders, reschedule chases and slot holds.</p>
                </div>
                <Button icon="pi pi-refresh" label="Refresh" className="p-button-sm p-button-info" onClick={() => load()} />
            </div>

            <ChatflowFilters
                value={filters} onChange={setFilters} onApply={apply} onClear={clear} busy={loading}
                organizations={organizations} statuses={STATUSES} kinds={KINDS}
                placeholder="Search node id…"
            />

            <div className="pt-card">
                {error ? <Message severity="error" text={error} style={{ width: "100%", marginBottom: 12 }} /> : null}
                {loading ? (
                    <div style={{ display: "flex", justifyContent: "center", padding: "40px 0" }}>
                        <ProgressSpinner style={{ width: "2.5rem", height: "2.5rem" }} />
                    </div>
                ) : (
                    <DataTable value={items} paginator rows={20} emptyMessage="No timers match these filters.">
                        <Column field="id" header="ID" style={{ width: 90 }} />
                        <Column header="Organization" body={orgBody} />
                        <Column header="Kind" body={(r) => <Tag value={TIMER_KIND_CODE[r.kind] || r.kind} severity={kindSeverity(r.kind)} />} style={{ width: 140 }} />
                        <Column header="Target" body={targetBody} />
                        <Column header="Fire at" body={dateBody("fire_at")} style={{ width: 190 }} />
                        <Column header="Status" body={(r) => <Tag value={TIMER_STATUS_CODE[r.status] || r.status} severity={statusSeverity(r.status)} />} style={{ width: 130 }} />
                        <Column header="Created" body={dateBody("created_at")} style={{ width: 190 }} />
                    </DataTable>
                )}
            </div>
        </div>
    );
};

export default Timer;
