import { useState } from "react";
import api from "../../../api/client";
import { fmtDate } from "./shared";

function fmtDateTimeGR(isoLocal) {
  // isoLocal is "YYYY-MM-DDTHH:MM" (value from datetime-local input)
  if (!isoLocal) return "";
  const d = new Date(isoLocal);
  if (Number.isNaN(d.getTime())) return "";
  return d.toLocaleString("el-GR", {
    day: "2-digit", month: "2-digit", year: "numeric",
    hour: "2-digit", minute: "2-digit", hour12: false,
  });
}

function DateTimeInput({ value, onChange, style }) {
  return (
    <div style={{ position: "relative" }}>
      <input type="datetime-local" value={value} onChange={onChange} style={{ ...style, color: "transparent", caretColor: "var(--text-primary)" }} />
      <div style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        display: "flex", alignItems: "center", paddingLeft: 10,
        fontSize: 13, color: "var(--text-primary)",
      }}>
        {fmtDateTimeGR(value)}
      </div>
    </div>
  );
}

const labelStyle = { fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em" };
const inputStyle = { backgroundColor: "var(--bg-input)", borderColor: "var(--border-primary)", color: "var(--text-primary)", border: "1px solid var(--border-primary)", borderRadius: 6, padding: "6px 10px", fontSize: 13, width: "100%" };

function DeleteConfirm({ onConfirm, onCancel, deleting }) {
  return (
    <div style={{ position: "fixed", inset: 0, backgroundColor: "rgba(0,0,0,0.6)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1001 }}>
      <div style={{ backgroundColor: "var(--bg-card)", borderRadius: 10, padding: 24, width: 340, border: "1px solid var(--border-primary)" }}>
        <p style={{ fontSize: 14, color: "var(--text-primary)", marginBottom: 18 }}>Delete this entry? This cannot be undone.</p>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button type="button" onClick={onCancel} style={{ fontSize: 13, padding: "5px 14px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
          <button type="button" onClick={onConfirm} disabled={deleting}
            style={{ fontSize: 13, fontWeight: 600, padding: "5px 14px", borderRadius: 6, border: "none", backgroundColor: "var(--danger)", color: "#fff", cursor: "pointer", opacity: deleting ? 0.6 : 1 }}>
            {deleting ? "Deleting..." : "Delete"}
          </button>
        </div>
      </div>
    </div>
  );
}

function IssueRow({ item, index, type, onResolve, onEdit, onDelete, canEdit }) {
  const [hovered, setHovered] = useState(false);
  const dotColor = item.active
    ? (type === "issue" ? "var(--crm-issue-active-text)" : "var(--crm-support-active-text)")
    : "var(--crm-resolved-text)";
  const rowBg = item.active
    ? (type === "issue" ? "var(--crm-issue-active-bg)" : "var(--crm-support-active-bg)")
    : "transparent";

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: "grid",
        gridTemplateColumns: "16px 1fr auto",
        gap: 12,
        alignItems: "start",
        padding: "10px 12px",
        borderRadius: 6,
        backgroundColor: rowBg,
        border: "1px solid",
        borderColor: item.active ? dotColor + "44" : "var(--border-secondary)",
        marginBottom: 6,
      }}>
      <div style={{ marginTop: 3, width: 10, height: 10, borderRadius: "50%", backgroundColor: dotColor, flexShrink: 0 }} />
      <div>
        <p style={{ fontSize: 13, color: "var(--text-primary)", marginBottom: 3, whiteSpace: "pre-wrap" }}>{item.note}</p>
        <p style={{ fontSize: 11, color: "var(--text-muted)" }}>
          Opened {fmtDate(item.opened_date)} by {item.opened_by}
          {!item.active && item.resolved_date && (
            <> · Resolved {fmtDate(item.resolved_date)}{item.resolved_by ? ` by ${item.resolved_by}` : ""}</>
          )}
        </p>
      </div>
      {canEdit && (
        <div style={{ display: "flex", gap: 4, flexShrink: 0, visibility: hovered ? "visible" : "hidden" }}>
          <button type="button" onClick={() => onEdit(index, item)}
            style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
            Edit
          </button>
          {item.active && (
            <button type="button" onClick={() => onResolve(index)}
              style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
              Resolve
            </button>
          )}
          <button type="button" onClick={() => onDelete(index)}
            style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 5, border: "1px solid var(--danger)", backgroundColor: "transparent", color: "var(--danger)", cursor: "pointer" }}>
            Delete
          </button>
        </div>
      )}
    </div>
  );
}

function IssueCard({ title, type, items, customerId, onUpdated, canEdit, user }) {
  const [showForm, setShowForm] = useState(false);
  const [note, setNote] = useState("");
  const [date, setDate] = useState(() => new Date().toISOString().slice(0, 16));
  const [saving, setSaving] = useState(false);
  const [resolving, setResolving] = useState(null);

  // Edit state
  const [editIndex, setEditIndex] = useState(null);
  const [editNote, setEditNote] = useState("");
  const [editDate, setEditDate] = useState("");
  const [editSaving, setEditSaving] = useState(false);

  // Delete state
  const [deleteIndex, setDeleteIndex] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const activeCount = (items || []).filter((i) => i.active).length;
  const sorted = [...(items || [])].sort((a, b) => (b.opened_date || "").localeCompare(a.opened_date || ""));
  const endpoint = type === "issue" ? "technical-issues" : "install-support";

  const handleSubmit = async () => {
    if (!note.trim()) return;
    setSaving(true);
    try {
      const updated = await api.post(`/crm/customers/${customerId}/${endpoint}`, {
        note: note.trim(),
        opened_by: user?.name || "Staff",
        date: new Date(date).toISOString(),
      });
      onUpdated(updated);
      setNote("");
      setDate(new Date().toISOString().slice(0, 16));
      setShowForm(false);
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleResolve = async (index) => {
    setResolving(index);
    try {
      const updated = await api.patch(`/crm/customers/${customerId}/${endpoint}/${index}/resolve`, {
        resolved_by: user?.name || "Staff",
      });
      onUpdated(updated);
    } catch (err) {
      alert(err.message);
    } finally {
      setResolving(null);
    }
  };

  const startEdit = (index, item) => {
    setEditIndex(index);
    setEditNote(item.note || "");
    setEditDate(item.opened_date ? new Date(item.opened_date).toISOString().slice(0, 16) : new Date().toISOString().slice(0, 16));
  };

  const handleEdit = async () => {
    if (!editNote.trim()) return;
    setEditSaving(true);
    try {
      const updated = await api.patch(`/crm/customers/${customerId}/${endpoint}/${editIndex}`, {
        note: editNote.trim(),
        opened_date: new Date(editDate).toISOString(),
      });
      onUpdated(updated);
      setEditIndex(null);
    } catch (err) {
      alert(err.message);
    } finally {
      setEditSaving(false);
    }
  };

  const handleDelete = async () => {
    setDeleting(true);
    try {
      const updated = await api.delete(`/crm/customers/${customerId}/${endpoint}/${deleteIndex}`);
      onUpdated(updated);
      setDeleteIndex(null);
    } catch (err) {
      alert(err.message);
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div className="ui-section-card mb-4">
      <div className="flex items-center justify-between mb-4">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-heading)" }}>{title}</span>
          {activeCount > 0 && (
            <span style={{
              fontSize: 11, fontWeight: 700, padding: "1px 8px", borderRadius: 10,
              backgroundColor: type === "issue" ? "var(--crm-issue-active-bg)" : "var(--crm-support-active-bg)",
              color: type === "issue" ? "var(--crm-issue-active-text)" : "var(--crm-support-active-text)",
            }}>
              {activeCount} active
            </span>
          )}
        </div>
        {canEdit && (
          <button type="button" onClick={() => setShowForm((v) => !v)}
            style={{ fontSize: 12, fontWeight: 600, padding: "4px 12px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: showForm ? "var(--bg-card-hover)" : "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
            + Report New
          </button>
        )}
      </div>

      {/* New entry form */}
      {showForm && (
        <div style={{ padding: 12, borderRadius: 8, marginBottom: 12, backgroundColor: "var(--bg-primary)", border: "1px solid var(--border-primary)" }}>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8 }}>
            <div style={{ flex: 1 }}>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Date</div>
              <DateTimeInput value={date} onChange={(e) => setDate(e.target.value)} style={inputStyle} />
            </div>
            <button type="button" onClick={() => setDate(new Date().toISOString().slice(0, 16))}
              style={{ marginTop: 20, fontSize: 11, padding: "6px 10px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", whiteSpace: "nowrap", flexShrink: 0 }}>
              Set Now
            </button>
          </div>
          <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} placeholder="Describe the issue..."
            style={{ width: "100%", padding: "8px 10px", borderRadius: 6, fontSize: 13, backgroundColor: "var(--bg-input)", borderColor: "var(--border-primary)", color: "var(--text-primary)", border: "1px solid var(--border-primary)", resize: "vertical" }} />
          <div className="flex gap-2 mt-2 justify-end">
            <button type="button" onClick={() => { setShowForm(false); setNote(""); setDate(new Date().toISOString().slice(0, 16)); }}
              style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>
              Cancel
            </button>
            <button type="button" onClick={handleSubmit} disabled={saving || !note.trim()}
              style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: saving ? 0.6 : 1 }}>
              {saving ? "Saving..." : "Submit"}
            </button>
          </div>
        </div>
      )}

      {/* Edit form */}
      {editIndex !== null && (
        <div style={{ padding: 12, borderRadius: 8, marginBottom: 12, backgroundColor: "var(--bg-primary)", border: "1px solid var(--accent)44" }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-heading)", marginBottom: 8 }}>Edit Entry</div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8 }}>
            <div style={{ flex: 1 }}>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Date</div>
              <DateTimeInput value={editDate} onChange={(e) => setEditDate(e.target.value)} style={inputStyle} />
            </div>
            <button type="button" onClick={() => setEditDate(new Date().toISOString().slice(0, 16))}
              style={{ marginTop: 20, fontSize: 11, padding: "6px 10px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", whiteSpace: "nowrap", flexShrink: 0 }}>
              Set Now
            </button>
          </div>
          <textarea value={editNote} onChange={(e) => setEditNote(e.target.value)} rows={3}
            style={{ width: "100%", padding: "8px 10px", borderRadius: 6, fontSize: 13, backgroundColor: "var(--bg-input)", color: "var(--text-primary)", border: "1px solid var(--border-primary)", resize: "vertical" }} />
          <div className="flex gap-2 mt-2 justify-end">
            <button type="button" onClick={() => setEditIndex(null)}
              style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>
              Cancel
            </button>
            <button type="button" onClick={handleEdit} disabled={editSaving || !editNote.trim()}
              style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: editSaving ? 0.6 : 1 }}>
              {editSaving ? "Saving..." : "Save"}
            </button>
          </div>
        </div>
      )}

      {sorted.length === 0 ? (
        <p style={{ fontSize: 13, color: "var(--text-muted)", fontStyle: "italic" }}>No entries.</p>
      ) : (
        <div style={{ maxHeight: sorted.length > 5 ? 360 : "none", overflowY: sorted.length > 5 ? "auto" : "visible" }}>
          {sorted.map((item, i) => {
            const origIdx = (items || []).findIndex((x) => x === item || (x.opened_date === item.opened_date && x.note === item.note));
            return (
              <IssueRow
                key={i}
                item={item}
                index={origIdx}
                type={type}
                onResolve={handleResolve}
                onEdit={startEdit}
                onDelete={(idx) => setDeleteIndex(idx)}
                canEdit={canEdit}
              />
            );
          })}
        </div>
      )}

      {deleteIndex !== null && (
        <DeleteConfirm onConfirm={handleDelete} onCancel={() => setDeleteIndex(null)} deleting={deleting} />
      )}
    </div>
  );
}

export default function SupportTab({ customer, canEdit, onCustomerUpdated, user }) {
  return (
    <div>
      <IssueCard title="Technical Issues" type="issue" items={customer.technical_issues || []} customerId={customer.id} onUpdated={onCustomerUpdated} canEdit={canEdit} user={user} />
      <IssueCard title="Install Support" type="support" items={customer.install_support || []} customerId={customer.id} onUpdated={onCustomerUpdated} canEdit={canEdit} user={user} />
    </div>
  );
}
