"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";

type ExportFormat = "txt" | "xlsx";

export function UserExportToolbar() {
  const [activeOnly, setActiveOnly] = useState(true);
  const [excludeAdmins, setExcludeAdmins] = useState(true);
  const [loading, setLoading] = useState<ExportFormat | null>(null);
  const [message, setMessage] = useState("");

  async function handleExport(format: ExportFormat) {
    setLoading(format);
    setMessage("");
    try {
      const params = new URLSearchParams({
        format,
        activeOnly: String(activeOnly),
        excludeAdmins: String(excludeAdmins),
      });
      const res = await fetch(`/api/admin/users/export?${params}`);
      if (!res.ok) {
        const data = (await res.json().catch(() => null)) as { error?: string } | null;
        setMessage(data?.error ?? "خطا در دریافت فایل");
        return;
      }

      const blob = await res.blob();
      const count = res.headers.get("X-Export-Count");
      const disposition = res.headers.get("Content-Disposition") ?? "";
      const match = disposition.match(/filename="([^"]+)"/);
      const filename = match?.[1] ?? `taroot-users.${format}`;

      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = filename;
      link.click();
      URL.revokeObjectURL(url);

      setMessage(
        count
          ? `${Number(count).toLocaleString("fa-IR")} شماره با موفقیت دانلود شد.`
          : "فایل با موفقیت دانلود شد."
      );
    } catch {
      setMessage("خطایی رخ داد. دوباره تلاش کنید.");
    } finally {
      setLoading(null);
    }
  }

  return (
    <div className="mb-6 rounded-lg border bg-card p-4 space-y-4">
      <div>
        <h2 className="font-semibold">خروجی شماره‌ها برای پیامک</h2>
        <p className="text-sm text-muted-foreground mt-1">
          شماره موبایل کاربران را برای ارسال پیامک تخفیف یا اطلاع‌رسانی دانلود کنید.
        </p>
      </div>

      <div className="flex flex-wrap gap-6">
        <label className="flex items-center gap-2 text-sm cursor-pointer">
          <input
            type="checkbox"
            checked={activeOnly}
            onChange={(e) => setActiveOnly(e.target.checked)}
            className="size-4 rounded border-input"
          />
          <Label className="cursor-pointer font-normal">فقط کاربران فعال</Label>
        </label>
        <label className="flex items-center gap-2 text-sm cursor-pointer">
          <input
            type="checkbox"
            checked={excludeAdmins}
            onChange={(e) => setExcludeAdmins(e.target.checked)}
            className="size-4 rounded border-input"
          />
          <Label className="cursor-pointer font-normal">بدون ادمین‌ها</Label>
        </label>
      </div>

      <div className="flex flex-wrap gap-3">
        <Button
          type="button"
          variant="outline"
          disabled={loading !== null}
          onClick={() => handleExport("txt")}
        >
          {loading === "txt" ? "در حال آماده‌سازی..." : "دانلود TXT"}
        </Button>
        <Button
          type="button"
          disabled={loading !== null}
          onClick={() => handleExport("xlsx")}
        >
          {loading === "xlsx" ? "در حال آماده‌سازی..." : "دانلود Excel"}
        </Button>
      </div>

      {message && (
        <p className="text-sm text-foreground" role="status">
          {message}
        </p>
      )}
    </div>
  );
}
