"use client";

import { useActionState, useState } from "react";
import { useFormStatus } from "react-dom";
import { addPlanItemAction, type PlanState } from "./actions";

export type CustomerOption = { id: string; orgName: string; code: string };

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" className="btn-primary px-3 py-1.5 text-xs" disabled={pending}>
      {pending ? "Đang lưu…" : "+ Thêm việc vào lộ trình"}
    </button>
  );
}

/**
 * Form thêm một điểm vào lộ trình tuần — chưa có kế hoạch thì `addPlanItemAction`
 * tự tạo luôn, không cần bước "khởi tạo kế hoạch tuần" riêng.
 *
 * Chỉ hiện khi NVKD đang xem lộ trình của chính mình (trang gọi component này đã
 * lọc điều kiện đó) — quản lý xem lộ trình người khác không thêm hộ được, khớp với
 * việc action luôn ghi theo `session.userId`, không nhận tham số người khác.
 */
export function AddPlanItemForm({
  days,
  dayLabels,
  customers,
}: {
  days: string[];
  dayLabels: string[];
  customers: CustomerOption[];
}) {
  const [state, formAction] = useActionState<PlanState, FormData>(addPlanItemAction, {});
  const [open, setOpen] = useState(false);

  if (!open) {
    return (
      <button type="button" onClick={() => setOpen(true)} className="btn-ghost text-xs">
        + Thêm việc vào lộ trình tuần
      </button>
    );
  }

  return (
    <form action={formAction} className="card flex flex-col gap-3 p-4">
      <div className="grid gap-3 lg:grid-cols-4">
        <div>
          <label htmlFor="planDate" className="label-caps mb-1.5 block">
            Ngày
          </label>
          <select id="planDate" name="planDate" required defaultValue={days[0]} className="input">
            {days.map((day, index) => (
              <option key={day} value={day}>
                {dayLabels[index]}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label htmlFor="timeSlot" className="label-caps mb-1.5 block">
            Khung giờ
          </label>
          <input id="timeSlot" name="timeSlot" placeholder="8:00-10:00" className="input" />
        </div>
        <div className="lg:col-span-2">
          <label htmlFor="customerId" className="label-caps mb-1.5 block">
            Khách hàng liên quan
          </label>
          <select id="customerId" name="customerId" defaultValue="" className="input">
            <option value="">— Không gắn khách hàng —</option>
            {customers.map((customer) => (
              <option key={customer.id} value={customer.id}>
                {customer.orgName} · {customer.code}
              </option>
            ))}
          </select>
        </div>
        <div className="lg:col-span-3">
          <label htmlFor="content" className="label-caps mb-1.5 block">
            Nội dung công việc
          </label>
          <input
            id="content"
            name="content"
            required
            placeholder="Ghé thăm giới thiệu sản phẩm mới, thu công nợ…"
            className="input"
          />
        </div>
        <div>
          <label htmlFor="objective" className="label-caps mb-1.5 block">
            Mục tiêu
          </label>
          <input id="objective" name="objective" placeholder="Chốt đơn, lấy phản hồi…" className="input" />
        </div>
      </div>

      {state.error && (
        <p role="alert" className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
          {state.error}
        </p>
      )}
      {state.ok && (
        <p className="rounded-lg bg-ink-100 px-3 py-2 text-sm text-brand-600">
          Đã thêm — cứ điền tiếp để thêm việc khác cho tuần này.
        </p>
      )}

      <div className="flex items-center gap-3">
        <SubmitButton />
        <button type="button" onClick={() => setOpen(false)} className="btn-ghost px-3 py-1.5 text-xs">
          Đóng
        </button>
      </div>
    </form>
  );
}
