"use client";

import { useState, useRef, useCallback } from "react";
import { Upload, File as FileIcon, X, Loader2 } from "lucide-react";

/** 文件上传组件 — 支持拖拽 + 点击上传。 */
export function FileUploader({ onParsed }: { onParsed: (result: any) => void }) {
  const [dragging, setDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const allowedTypes = [".xlsx", ".xls", ".pdf", ".txt", ".md", ".csv"];

  const handleFile = useCallback(async (f: File) => {
    const ext = f.name.match(/\.[^.]+$/)?.[0]?.toLowerCase() || "";
    if (!allowedTypes.includes(ext)) {
      return;
    }
    setFile(f);
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append("file", f);
      const token = localStorage.getItem("token");
      const resp = await fetch("/api/v1/reports/upload", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });
      const data = await resp.json();
      onParsed(data.data);
    } catch {
      // ignore
    } finally {
      setUploading(false);
    }
  }, [onParsed]);

  return (
    <div
      className="rounded-lg border-2 border-dashed border-[var(--border)] p-6 text-center transition-colors"
      onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
      onDragLeave={() => setDragging(false)}
      onDrop={(e) => {
        e.preventDefault();
        setDragging(false);
        if (e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
      }}
      style={dragging ? { borderColor: "var(--investor-primary)", background: "var(--investor-primary)/5" } : {}}
    >
      {file ? (
        <div className="flex items-center justify-between rounded-md border border-[var(--border)] bg-white px-3 py-2">
          <div className="flex items-center gap-2">
            <FileIcon size={16} className="text-[var(--investor-primary)]" />
            <span className="text-sm">{file.name}</span>
          </div>
          <div className="flex items-center gap-2">
            {uploading && <Loader2 size={14} className="animate-spin text-muted-foreground" />}
            <button
              onClick={() => { setFile(null); onParsed(null); }}
              className="text-muted-foreground hover:text-foreground"
              aria-label="移除文件"
            >
              <X size={14} />
            </button>
          </div>
        </div>
      ) : (
        <button
          onClick={() => inputRef.current?.click()}
          className="flex flex-col items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
        >
          <Upload size={24} />
          <span>点击或拖拽文件到此处上传</span>
          <span className="text-xs">支持 .xlsx .pdf .txt .csv .md（最大 10MB）</span>
        </button>
      )}
      <input
        ref={inputRef}
        type="file"
        accept=".xlsx,.xls,.pdf,.txt,.md,.csv"
        className="hidden"
        onChange={(e) => { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
      />
    </div>
  );
}
