/* global React, Icon, DB */
const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

const PRIORITY_COLOR = {
  high:   { bg: "#fee2e2", text: "#b91c1c", label: "ด่วน" },
  normal: { bg: "var(--surface-2)", text: "var(--ink-2)", label: "ปกติ" },
  low:    { bg: "var(--surface-2)", text: "var(--ink-3)", label: "ไม่ด่วน" },
};

function TaskItem({ task, onToggle, onDelete }) {
  const pc = PRIORITY_COLOR[task.priority] || PRIORITY_COLOR.normal;
  return (
    <div style={{
      display: "flex", alignItems: "flex-start", gap: 10,
      padding: "10px 12px", borderRadius: 10,
      background: task.done ? "transparent" : pc.bg,
      border: "1px solid",
      borderColor: task.done ? "var(--border)" : (task.priority === "high" ? "#fca5a5" : "var(--border)"),
      opacity: task.done ? 0.55 : 1,
      transition: "all .18s",
    }}>
      <button
        onClick={() => onToggle(task)}
        style={{
          width: 20, height: 20, borderRadius: 6, border: "2px solid",
          borderColor: task.done ? "var(--accent)" : (task.priority === "high" ? "#ef4444" : "var(--ink-3)"),
          background: task.done ? "var(--accent)" : "transparent",
          cursor: "pointer", flexShrink: 0, marginTop: 1,
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: 0, color: "#fff",
        }}>
        {task.done && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: "0.9rem", fontWeight: task.done ? 400 : 500,
          textDecoration: task.done ? "line-through" : "none",
          color: task.done ? "var(--ink-3)" : "var(--ink-1)",
          lineHeight: 1.4,
          wordBreak: "break-word",
        }}>{task.text}</div>
        <div style={{ display: "flex", gap: 6, marginTop: 4, alignItems: "center", flexWrap: "wrap" }}>
          {task.priority === "high" && !task.done && (
            <span style={{ fontSize: "0.7rem", fontWeight: 600, color: "#b91c1c", background: "#fee2e2", padding: "1px 6px", borderRadius: 99 }}>⚡ ด่วน</span>
          )}
          {task.created_at && (
            <span style={{ fontSize: "0.72rem", color: "var(--ink-3)" }}>
              {task.created_at.slice(11, 16)} · {task.created_at.slice(5, 10).replace("-", "/")}
            </span>
          )}
          {task.created_by && (
            <span style={{ fontSize: "0.72rem", color: "var(--ink-3)" }}>— {task.created_by}</span>
          )}
        </div>
      </div>
      <button
        onClick={() => onDelete(task.id)}
        style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", padding: 2, flexShrink: 0, lineHeight: 1 }}
        title="ลบ">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
  );
}

function TaskPanel({ open, onClose, tasks, setTasks }) {
  const [text, setText] = useStateT("");
  const [priority, setPriority] = useStateT("normal");
  const [saving, setSaving] = useStateT(false);
  const inputRef = useRefT(null);

  useEffectT(() => {
    if (open && inputRef.current) setTimeout(() => inputRef.current?.focus(), 80);
  }, [open]);

  if (!open) return null;

  const pending = tasks.filter(t => !t.done);
  const done    = tasks.filter(t => t.done);

  const handleAdd = async () => {
    if (!text.trim()) return;
    setSaving(true);
    try {
      const res = await DB.addTask({ text: text.trim(), priority });
      const newTask = { id: res.id, text: text.trim(), priority, done: 0, created_at: new Date(Date.now() + 7*3600000).toISOString().slice(0,19).replace("T"," "), created_by: "" };
      setTasks(prev => [newTask, ...prev]);
      setText("");
      setPriority("normal");
    } catch(e) { console.error(e); }
    setSaving(false);
  };

  const handleToggle = async (task) => {
    const newDone = task.done ? 0 : 1;
    setTasks(prev => prev.map(t => t.id === task.id ? { ...t, done: newDone } : t));
    DB.updateTask(task.id, { done: newDone }).catch(console.error);
  };

  const handleDelete = async (id) => {
    setTasks(prev => prev.filter(t => t.id !== id));
    DB.deleteTask(id).catch(console.error);
  };

  const clearDone = async () => {
    const ids = done.map(t => t.id);
    setTasks(prev => prev.filter(t => !t.done));
    ids.forEach(id => DB.deleteTask(id).catch(console.error));
  };

  return (
    <div
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 1100,
        background: "rgba(0,0,0,.32)", backdropFilter: "blur(2px)",
        display: "flex", alignItems: "flex-start", justifyContent: "flex-start",
      }}>
      <div style={{
        width: 380, maxWidth: "95vw", height: "100vh",
        background: "var(--surface-1)", display: "flex", flexDirection: "column",
        boxShadow: "4px 0 32px rgba(0,0,0,.18)",
        animation: "slideInLeft .18s ease-out",
      }}>
        {/* Header */}
        <div style={{ padding: "18px 20px 14px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "var(--accent)", display: "grid", placeItems: "center", color: "#fff", flexShrink: 0 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: "1rem" }}>สิ่งที่ต้องทำ</div>
            <div style={{ fontSize: "0.78rem", color: "var(--ink-3)" }}>ส่งต่อให้พนักงานกะถัดไป</div>
          </div>
          <button className="btn ghost sm" onClick={onClose}>✕</button>
        </div>

        {/* Add input */}
        <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 8 }}>
          <textarea
            ref={inputRef}
            value={text}
            onChange={e => setText(e.target.value)}
            onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleAdd(); } }}
            placeholder="พิมพ์สิ่งที่ต้องทำ... (Enter เพื่อเพิ่ม)"
            rows={2}
            style={{
              width: "100%", resize: "none", padding: "10px 12px",
              border: "1.5px solid var(--border)", borderRadius: 10,
              background: "var(--surface-2)", color: "var(--ink-1)",
              fontSize: "0.9rem", fontFamily: "inherit",
              outline: "none", boxSizing: "border-box",
            }}
          />
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <div style={{ display: "flex", gap: 4, flex: 1 }}>
              {["normal", "high", "low"].map(p => (
                <button key={p}
                  onClick={() => setPriority(p)}
                  className="btn sm"
                  style={{
                    background: priority === p ? "var(--accent)" : "var(--surface-2)",
                    color: priority === p ? "#fff" : "var(--ink-2)",
                    border: "1px solid",
                    borderColor: priority === p ? "var(--accent)" : "var(--border)",
                    fontWeight: priority === p ? 600 : 400,
                    fontSize: "0.78rem",
                  }}>
                  {p === "high" ? "⚡ ด่วน" : p === "low" ? "ไม่ด่วน" : "ปกติ"}
                </button>
              ))}
            </div>
            <button
              className="btn primary sm"
              onClick={handleAdd}
              disabled={saving || !text.trim()}
              style={{ whiteSpace: "nowrap" }}>
              + เพิ่ม
            </button>
          </div>
        </div>

        {/* Task list */}
        <div style={{ flex: 1, overflowY: "auto", padding: "12px 16px", display: "flex", flexDirection: "column", gap: 8 }}>
          {tasks.length === 0 && (
            <div style={{ textAlign: "center", padding: "40px 0", color: "var(--ink-3)" }}>
              <div style={{ fontSize: "2rem", marginBottom: 10 }}>✅</div>
              <div style={{ fontSize: "0.9rem" }}>ไม่มีงานที่ค้างอยู่</div>
            </div>
          )}

          {pending.length > 0 && (
            <>
              <div style={{ fontSize: "0.78rem", fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", padding: "2px 0" }}>
                รอดำเนินการ · {pending.length} รายการ
              </div>
              {pending.map(t => (
                <TaskItem key={t.id} task={t} onToggle={handleToggle} onDelete={handleDelete}/>
              ))}
            </>
          )}

          {done.length > 0 && (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
                <div style={{ fontSize: "0.78rem", fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>
                  เสร็จแล้ว · {done.length} รายการ
                </div>
                <button className="btn sm" onClick={clearDone} style={{ fontSize: "0.75rem", color: "var(--danger)", borderColor: "var(--danger)", background: "transparent" }}>
                  ล้างทั้งหมด
                </button>
              </div>
              {done.map(t => (
                <TaskItem key={t.id} task={t} onToggle={handleToggle} onDelete={handleDelete}/>
              ))}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.TaskPanel = TaskPanel;
