"use client";

import { useRef } from "react";
import { ActionForm } from "@/components/action-form";
import { useToast } from "@/components/toast";
import { DOCUMENT_CATEGORIES, DOCUMENT_FILE_ACCEPT, DOCUMENT_MAX_MB, formatFileSize } from "@/lib/document-categories";
import { uploadCompanyDocumentAction } from "./actions";

/**
 * Form tải văn bản lên. Kiểm dung lượng ngay khi chọn tệp: tệp quá lớn bị Next chặn trước khi tới action,
 * người dùng chỉ thấy lỗi chung chung — nên báo sớm ở trình duyệt.
 */
export function DocumentUploadForm({ defaultCategory }: { defaultCategory: string }) {
  const fileInput = useRef<HTMLInputElement>(null);
  const toast = useToast();

  function checkSize() {
    const file = fileInput.current?.files?.[0];
    if (file && file.size > DOCUMENT_MAX_MB * 1024 * 1024) {
      toast.error(`Tệp ${formatFileSize(file.size)} vượt quá ${DOCUMENT_MAX_MB} MB — hãy nén hoặc chia nhỏ tệp.`);
      if (fileInput.current) fileInput.current.value = "";
    }
  }

  return (
    <ActionForm action={uploadCompanyDocumentAction} success="Đã tải văn bản lên." resetOnSuccess className="card mt-4 grid gap-3 p-4 lg:grid-cols-2">
      <div className="lg:col-span-2 text-sm font-semibold text-ink-700">Tải văn bản mới</div>
      <div>
        <label htmlFor="doc-title" className="label-caps mb-1.5 block">
          Tên văn bản
        </label>
        <input id="doc-title" name="title" type="text" required maxLength={200} placeholder="Ví dụ: Quy chế bán hàng 2026" className="input" />
      </div>
      <div>
        <label htmlFor="doc-category" className="label-caps mb-1.5 block">
          Loại
        </label>
        <select id="doc-category" name="category" defaultValue={defaultCategory} className="input">
          {DOCUMENT_CATEGORIES.map((c) => (
            <option key={c.key} value={c.key}>
              {c.label}
            </option>
          ))}
        </select>
      </div>
      <div className="lg:col-span-2">
        <label htmlFor="doc-description" className="label-caps mb-1.5 block">
          Trích yếu (không bắt buộc)
        </label>
        <textarea id="doc-description" name="description" rows={2} maxLength={1000} placeholder="Nội dung chính, đối tượng áp dụng, hiệu lực từ ngày…" className="input" />
      </div>
      <div className="lg:col-span-2">
        <label htmlFor="doc-file" className="label-caps mb-1.5 block">
          Tệp đính kèm
        </label>
        <input id="doc-file" ref={fileInput} name="file" type="file" required accept={DOCUMENT_FILE_ACCEPT} onChange={checkSize} className="input" />
        <p className="mt-1.5 text-[11px] text-ink-400">PDF, ảnh PNG/JPEG, Word (.docx), Excel (.xlsx) hoặc PowerPoint (.pptx) — tối đa {DOCUMENT_MAX_MB}MB.</p>
      </div>
      <div className="lg:col-span-2">
        <button type="submit" className="btn-primary">
          Tải văn bản lên
        </button>
      </div>
    </ActionForm>
  );
}
