"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { ShieldCheck, Plus, FileText, ArrowUpCircle, X } from "lucide-react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { useApp } from "@/components/app-context";
import { suggestForFile, toolById } from "@/data/tools";
import { fmtBytes } from "@/lib/files";

export function Hero({ onOpenTool }: { onOpenTool: (id: string, file?: File) => void }) {
  const { T, lang } = useApp();
  const [dragOver, setDragOver] = useState(false);
  const [suggestions, setSuggestions] = useState<{ file: File; ids: string[] } | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);

  const handleFiles = useCallback((files: FileList | null) => {
    if (!files || !files.length) return;
    const file = files[0];
    const ids = suggestForFile(file).map((t) => t.id);
    if (ids.length) setSuggestions({ file, ids });
    else onOpenTool(ids[0] ?? "create-zip", file);
    if (!ids.length) return;
  }, [onOpenTool]);

  useEffect(() => {
    const onDrop = (e: DragEvent) => {
      const card = cardRef.current;
      if (!card) return;
      const inCard = e.clientX >= 0 && document.elementFromPoint(e.clientX, e.clientY)?.closest("#hero-card");
      if (inCard) return; // handled locally
    };
    window.addEventListener("drop", onDrop);
    return () => window.removeEventListener("drop", onDrop);
  }, []);

  return (
    <section
      className="relative overflow-hidden"
    >
      <div className="mx-auto max-w-7xl px-4 pb-8 pt-14 text-center sm:px-6 sm:pt-20">
        <h1 className="text-[44px] font-extrabold leading-[1.06] tracking-tight text-zinc-950 dark:text-white sm:text-[64px] lg:text-[76px]">
          {T("heroLine1")}
          <br />
          <span className="text-[#15803d] dark:text-emerald-400">{T("heroLine2")}</span>
        </h1>
        <p className="mx-auto mt-5 max-w-2xl text-[16.5px] text-zinc-600 dark:text-zinc-300 sm:text-lg">{T("heroSub")}</p>

        <div
          id="hero-card"
          ref={cardRef}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => {
            e.preventDefault();
            setDragOver(false);
            handleFiles(e.dataTransfer.files);
          }}
          className={`mx-auto mt-9 max-w-3xl rounded-[26px] bg-white p-3 shadow-[0_20px_60px_-15px_rgba(15,80,50,0.25)] ring-1 ring-black/5 transition-transform dark:bg-[#12201a] dark:ring-white/10 ${dragOver ? "scale-[1.01]" : ""}`}
        >
          <div className={`rounded-[20px] border-2 border-dashed px-6 py-12 transition-colors dark:bg-transparent sm:py-14 ${dragOver ? "border-emerald-500 bg-emerald-50/60 dark:bg-emerald-500/5" : "border-zinc-200 dark:border-white/10"}`}>
            <div className="relative mx-auto mb-6 w-fit">
              <div className="relative h-20 w-20">
                <span className="absolute left-0 top-2 h-16 w-13 rotate-[-8deg] rounded-lg border-2 border-zinc-200 bg-white dark:border-white/20 dark:bg-[#182b22]" />
                <span className="absolute right-0 top-0 flex h-16 w-13 rotate-[6deg] flex-col items-start gap-1 rounded-lg border-2 border-zinc-200 bg-white p-2 dark:border-white/20 dark:bg-[#182b22]">
                  <span className="h-1.5 w-6 rounded bg-emerald-500/80" />
                  <span className="h-1.5 w-8 rounded bg-zinc-200 dark:bg-white/15" />
                  <span className="h-1.5 w-5 rounded bg-zinc-200 dark:bg-white/15" />
                </span>
              </div>
              <span className="absolute -bottom-2 left-1/2 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full bg-[#0b8a47] shadow-lg shadow-emerald-600/30">
                <ArrowUpCircle className="h-5 w-5 text-white" />
              </span>
            </div>

            <button
              onClick={() => inputRef.current?.click()}
              className="mx-auto flex h-12 items-center gap-2 rounded-xl bg-[#0b7a43] px-7 text-[16px] font-bold text-white shadow-md shadow-emerald-700/20 transition-all hover:bg-[#096c3b] active:scale-[0.98]"
            >
              <Plus className="h-5 w-5" strokeWidth={2.5} />
              {T("chooseFile")}
            </button>
            <input
              ref={inputRef}
              type="file"
              className="hidden"
              onChange={(e) => { handleFiles(e.target.files); e.currentTarget.value = ""; }}
            />
            <p className="mt-3 text-[14px] text-zinc-500 dark:text-zinc-400">{T("orDrop")}</p>
            <p className="mt-6 flex items-center justify-center gap-1.5 text-[13px] font-medium text-zinc-500 dark:text-zinc-400">
              <ShieldCheck className="h-4 w-4 text-[#0b8a47]" />
              {T("freeNote")}
            </p>
          </div>
        </div>
      </div>

      <Dialog open={!!suggestions} onOpenChange={(v) => !v && setSuggestions(null)}>
        <DialogContent className="max-w-md rounded-2xl p-0 [&>button]:hidden">
          {suggestions && (
            <>
              <div className="flex items-start justify-between gap-3 border-b border-zinc-100 p-5 dark:border-white/10">
                <div className="flex min-w-0 items-center gap-3">
                  <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-emerald-50 dark:bg-emerald-500/10">
                    <FileText className="h-5 w-5 text-emerald-700 dark:text-emerald-400" />
                  </span>
                  <div className="min-w-0">
                    <DialogTitle className="truncate text-[15px] font-bold">{suggestions.file.name}</DialogTitle>
                    <p className="text-[12px] text-zinc-500">{fmtBytes(suggestions.file.size)} · {T("pickToolForFile")}</p>
                  </div>
                </div>
                <button onClick={() => setSuggestions(null)} className="rounded-full p-1 text-zinc-400 hover:bg-zinc-100 dark:hover:bg-white/10" aria-label={T("close")}>
                  <X className="h-4 w-4" />
                </button>
              </div>
              <div className="max-h-[50vh] overflow-y-auto p-3">
                <p className="px-2 pb-1.5 text-[11px] font-bold uppercase tracking-wide text-emerald-700 dark:text-emerald-400">{T("suggested")}</p>
                <div className="grid grid-cols-2 gap-1.5">
                  {suggestions.ids.map((id) => {
                    const tool = toolById[id];
                    if (!tool) return null;
                    return (
                      <button
                        key={id}
                        onClick={() => { const f = suggestions.file; setSuggestions(null); onOpenTool(id, f); }}
                        className="rounded-xl border border-zinc-100 px-3 py-2.5 text-left transition-colors hover:border-emerald-300 hover:bg-emerald-50/60 dark:border-white/10 dark:hover:border-emerald-500/40 dark:hover:bg-emerald-500/10"
                      >
                        <span className="block truncate text-[13.5px] font-semibold">{tool.name[lang]}</span>
                        <span className="block truncate text-[11.5px] text-zinc-500 dark:text-zinc-400">{tool.desc[lang]}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>
    </section>
  );
}
