// src/components/storage/ZipModal.jsx
import React, { useMemo } from "react";
import { IoArchiveOutline, IoFileTray, IoFolderOpen } from "react-icons/io5";
import { TbPlus, TbRefresh, TbX } from "react-icons/tb";
import ModalShell from "./ModalShell";

export default function ZipModal({
  state,
  setState,
  files,
  allFoldersFlat,
  onCreateArchive,
}) {
  const open = !!state?.open;
  if (!open) return null;

  const zipSelectableOptions = useMemo(() => {
    const fileOpts = (files || []).map((f) => ({
      key: `file:${String(f.id)}`,
      type: "file",
      id: String(f.id),
      name: f?.name || "file",
      meta: f?.folderPath || "ریشه",
    }));

    const folderOpts = (allFoldersFlat || [])
      .filter((x) => x?.id)
      .map((fo) => ({
        key: `folder:${String(fo.id)}`,
        type: "folder",
        id: String(fo.id),
        name: fo?.name || "folder",
        meta: `depth:${fo.depth}`,
      }));

    const picked = new Set((state.items || []).map((it) => `${it.type}:${String(it.id)}`));
    return [...folderOpts, ...fileOpts].filter((o) => !picked.has(`${o.type}:${String(o.id)}`));
  }, [files, allFoldersFlat, state.items]);

  const addPickedToZipList = () => {
    const v = String(state.pickValue || "");
    if (!v) return;
    const opt = zipSelectableOptions.find((o) => o.key === v);
    if (!opt) return;
    const [type, id] = v.split(":");

    setState((p) => ({
      ...p,
      items: [...(p.items || []), { type, id, name: opt.name }],
      picking: false,
      pickValue: "",
    }));
  };

  return (
    <ModalShell
      open={open}
      title="فشرده‌سازی (Zip)"
      onClose={() => !state.zipping && setState({
        open: false,
        items: [],
        name: "my-archive.zip",
        folder_id: "root",
        picking: false,
        pickValue: "",
        zipping: false,
      })}
      maxWidth="max-w-xl"
    >
      <div className="space-y-3 text-sm">
        <div className="rounded-2xl border border-black/10 dark:border-white/10 p-3 bg-white/60 dark:bg-[#16325B]/50">
          <div className="font-extrabold mb-2">موارد انتخاب‌شده</div>

          {(state.items || []).length === 0 ? (
            <div className="text-black/60 dark:text-white/60">موردی انتخاب نشده.</div>
          ) : (
            <div className="space-y-2">
              {(state.items || []).map((it) => (
                <div
                  key={`${it.type}:${it.id}`}
                  className="flex items-center justify-between gap-2 rounded-xl border border-black/10 dark:border-white/10 bg-white dark:bg-[#001F3F] px-3 py-2"
                >
                  <div className="min-w-0 flex items-center gap-2">
                    {it.type === "folder" ? <IoFolderOpen className="text-[#43BEFF]" /> : <IoFileTray className="text-[#43BEFF]" />}
                    <div className="truncate">
                      <span className="font-bold">{it.type === "folder" ? "پوشه:" : "فایل:"}</span> {it.name}
                    </div>
                  </div>

                  <button
                    type="button"
                    className="p-2 rounded-xl hover:bg-black/5 dark:hover:bg-white/10"
                    onClick={() => {
                      setState((p) => ({
                        ...p,
                        items: (p.items || []).filter((x) => !(x.type === it.type && String(x.id) === String(it.id))),
                      }));
                    }}
                    title="حذف از لیست"
                  >
                    <TbX className="w-5 h-5" />
                  </button>
                </div>
              ))}
            </div>
          )}

          <div className="mt-3">
            {!state.picking ? (
              <button
                type="button"
                className="w-full px-4 py-2 rounded-xl shadow bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 inline-flex items-center justify-center gap-2"
                onClick={() => setState((p) => ({ ...p, picking: true }))}
              >
                <TbPlus className="w-5 h-5 text-[#43BEFF]" />
                افزودن فایل/پوشه دیگر
              </button>
            ) : (
              <div className="flex gap-2">
                <select
                  value={state.pickValue}
                  onChange={(e) => setState((p) => ({ ...p, pickValue: e.target.value }))}
                  className="flex-1 rounded-xl border border-black/10 dark:border-white/10 bg-white dark:bg-[#001F3F] px-3 py-2 outline-none dark:text-white"
                >
                  <option value="">انتخاب کنید...</option>
                  {zipSelectableOptions.map((o) => (
                    <option key={o.key} value={o.key}>
                      {o.type === "folder" ? "📁 " : "📄 "}
                      {o.name}
                    </option>
                  ))}
                </select>

                <button
                  type="button"
                  className="px-4 py-2 rounded-xl bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
                  onClick={addPickedToZipList}
                  disabled={!state.pickValue}
                >
                  افزودن
                </button>

                <button
                  type="button"
                  className="px-4 py-2 rounded-xl border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
                  onClick={() => setState((p) => ({ ...p, picking: false, pickValue: "" }))}
                >
                  لغو
                </button>
              </div>
            )}
          </div>
        </div>

        <div className="flex gap-2 justify-end pt-1">
          <button
            type="button"
            className="px-4 py-2 rounded-xl shadow dark:text-white border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
            disabled={state.zipping}
            onClick={() => setState({
              open: false,
              items: [],
              name: "my-archive.zip",
              folder_id: "root",
              picking: false,
              pickValue: "",
              zipping: false,
            })}
          >
            لغو
          </button>

          <button
            type="button"
            className="px-4 py-2 rounded-xl shadow dark:text-white bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 inline-flex items-center gap-2"
            disabled={state.zipping}
            onClick={onCreateArchive}
          >
            {state.zipping ? (
              <>
                <TbRefresh className="w-4 h-4 animate-spin text-[#43BEFF]" />
                در حال زیپ...
              </>
            ) : (
              <>
                <IoArchiveOutline className="text-[#43BEFF]" />
                فشرده‌سازی
              </>
            )}
          </button>
        </div>
      </div>
    </ModalShell>
  );
}
