import React, { useMemo, useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import EntityModal from "../../components/common/EntityModal.jsx";
import useMasterData from "../../hooks/useMasterData.js";
import { listTickets, updateTicket } from "../../services/ticketsApi.js";

function toMysqlDateTime(date) {
  return date.toISOString().slice(0, 19).replace("T", " ");
}

export default function AdminTicketListPage({ onNavigate }) {
  const { data } = useMasterData();
  const [tickets, setTickets] = useState([]);
  const [selected, setSelected] = useState(null);
  const [error, setError] = useState("");
  const [editOpen, setEditOpen] = useState(false);
  const [filterStatus, setFilterStatus] = useState("");
  const [draft, setDraft] = useState({ description: "", ticket_type_id: "", status_id: "" });

  const statusOptions = useMemo(() => data.tickets_status || [], [data.tickets_status]);
  const typeOptions = useMemo(() => data.tickets_type || [], [data.tickets_type]);
  const statusById = useMemo(
    () => Object.fromEntries(statusOptions.map((row) => [String(row.status_id), row.status_type])),
    [statusOptions]
  );
  const closedStatusId = useMemo(
    () => statusOptions.find((row) => /(closed|resolved)/i.test(row.status_type || ""))?.status_id || "",
    [statusOptions]
  );

  const load = React.useCallback(async () => {
    try {
      setError("");
      const rows = await listTickets(filterStatus ? { status_id: filterStatus } : {});
      setTickets(rows);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }, [filterStatus]);

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

  const openEdit = () => {
    if (!selected) return;
    setDraft({
      description: selected.description || "",
      ticket_type_id: selected.ticket_type_id ? String(selected.ticket_type_id) : "",
      status_id: selected.status_id ? String(selected.status_id) : ""
    });
    setEditOpen(true);
  };

  const saveUpdate = async () => {
    if (!selected) return;
    try {
      await updateTicket(selected.id, {
        description: draft.description,
        ticket_type_id: draft.ticket_type_id ? Number(draft.ticket_type_id) : null,
        status_id: draft.status_id ? Number(draft.status_id) : null
      });
      setEditOpen(false);
      await load();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  };

  const resolveTicket = async () => {
    if (!selected || !closedStatusId) return;
    try {
      await updateTicket(selected.id, { status_id: Number(closedStatusId), closed_at: toMysqlDateTime(new Date()) });
      await load();
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  };

  return (
    <div className="portal-page">
      <PageHeader
        title="Ticket List"
        subtitle="View ticket progress and update or resolve tickets."
        actions={(
          <>
            <button type="button" className="swi-btn" onClick={() => onNavigate("raise-ticket")}>Raise Ticket</button>
            <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Refresh</button>
          </>
        )}
      />
      <ErrorBanner message={error} />
      <div className="ptw-panel">
        <div className="ptw-toolbar">
          <select className="swi-input" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)}>
            <option value="">All statuses</option>
            {statusOptions.map((s) => <option key={s.status_id} value={s.status_id}>{s.status_type}</option>)}
          </select>
          <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Apply</button>
          <div className="ptw-toolbar__spacer" />
          <button type="button" className="swi-btn" onClick={openEdit} disabled={!selected}>Update</button>
          <button type="button" className="swi-btn" onClick={resolveTicket} disabled={!selected || !closedStatusId}>Resolve</button>
          <button type="button" className="swi-btn swi-btn--ghost" onClick={() => selected && onNavigate("ticket-logs", { ticketId: selected.id })} disabled={!selected}>View Logs</button>
        </div>

        <DataTable
          columns={[
            { key: "id", label: "ID" },
            { key: "description", label: "Description" },
            {
              key: "ticket_type_id",
              label: "Type",
              render: (row) => typeOptions.find((t) => Number(t.type_id) === Number(row.ticket_type_id))?.type_name || row.ticket_type_id || ""
            },
            {
              key: "status_id",
              label: "Status",
              render: (row) => (
                <span className="ptw-status-badge">{statusById[String(row.status_id)] || row.status_id || "Unknown"}</span>
              )
            },
            { key: "created_at", label: "Created" },
            { key: "closed_at", label: "Closed" }
          ]}
          rows={tickets}
          keyField="id"
          onRowClick={setSelected}
        />
        {selected ? (
          <p className="ptw-muted" style={{ marginTop: "0.75rem" }}>
            Progress: <strong>{statusById[String(selected.status_id)] || "Unknown"}</strong> | Ticket #{selected.id}
          </p>
        ) : null}
      </div>

      <EntityModal open={editOpen} title="Update Ticket" onClose={() => setEditOpen(false)}>
        <div className="ptw-form-grid-2">
          <label className="swi-field" style={{ gridColumn: "1 / -1" }}>
            <span className="swi-field__label">Description</span>
            <textarea className="swi-input" rows={4} value={draft.description} onChange={(e) => setDraft((prev) => ({ ...prev, description: e.target.value }))} />
          </label>
          <label className="swi-field">
            <span className="swi-field__label">Ticket type</span>
            <select className="swi-input" value={draft.ticket_type_id} onChange={(e) => setDraft((prev) => ({ ...prev, ticket_type_id: e.target.value }))}>
              <option value="">Select type</option>
              {typeOptions.map((t) => <option key={t.type_id} value={t.type_id}>{t.type_name}</option>)}
            </select>
          </label>
          <label className="swi-field">
            <span className="swi-field__label">Status</span>
            <select className="swi-input" value={draft.status_id} onChange={(e) => setDraft((prev) => ({ ...prev, status_id: e.target.value }))}>
              <option value="">Select status</option>
              {statusOptions.map((s) => <option key={s.status_id} value={s.status_id}>{s.status_type}</option>)}
            </select>
          </label>
        </div>
        <div className="ptw-row-actions" style={{ marginTop: "1rem" }}>
          <button type="button" className="swi-btn" onClick={saveUpdate}>Save</button>
        </div>
      </EntityModal>
    </div>
  );
}
