import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { CheckCircle2, Download, FileSpreadsheet, Loader2, Upload } from "lucide-react";
import { useRecipeManagement } from "@/hooks/useRecipeManagement";

export function ExcelImportPanel() {
  const { t } = useTranslation();
  const fileRef = useRef<HTMLInputElement>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [downloading, setDownloading] = useState(false);
  const {
    importExcel,
    importPending,
    importError,
    importResult,
    resetImport,
    downloadTemplate,
  } = useRecipeManagement();

  const handleDownloadTemplate = async () => {
    setDownloading(true);
    try {
      const blob = await downloadTemplate();
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "DailyMeals-recipe-import-template.xlsx";
      link.click();
      URL.revokeObjectURL(url);
    } finally {
      setDownloading(false);
    }
  };

  const handleImport = async () => {
    if (!selectedFile) return;
    resetImport();
    await importExcel(selectedFile);
    setSelectedFile(null);
    if (fileRef.current) fileRef.current.value = "";
  };

  return (
    <div className="space-y-6">
      <section className="card p-6">
        <div className="flex items-start gap-4">
          <div className="grid h-12 w-12 shrink-0 place-items-center rounded-xl bg-brand-100 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300">
            <FileSpreadsheet className="h-6 w-6" />
          </div>
          <div className="flex-1">
            <h2 className="text-lg font-bold">{t("manage.importTitle")}</h2>
            <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t("manage.importDescription")}</p>
            <button
              type="button"
              onClick={() => void handleDownloadTemplate()}
              disabled={downloading}
              className="btn-secondary mt-4"
            >
              {downloading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
              {t("manage.downloadTemplate")}
            </button>
          </div>
        </div>
      </section>

      <section className="card space-y-4 p-6">
        <label className="block text-sm font-medium">{t("manage.uploadLabel")}</label>
        <input
          ref={fileRef}
          type="file"
          accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          className="block w-full text-sm text-slate-500 file:mr-4 file:rounded-lg file:border-0 file:bg-brand-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-brand-700 hover:file:bg-brand-100 dark:file:bg-brand-900/40 dark:file:text-brand-300"
          onChange={(e) => setSelectedFile(e.target.files?.[0] ?? null)}
        />

        {importError && (
          <div role="alert" className="rounded-xl bg-red-50 p-3 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300">
            {importError}
          </div>
        )}

        {importResult && (
          <div className="rounded-xl border border-brand-200 bg-brand-50 p-4 dark:border-brand-800 dark:bg-brand-950/30">
            <div className="flex items-center gap-2 font-semibold text-brand-800 dark:text-brand-200">
              <CheckCircle2 className="h-5 w-5" />
              {t("manage.importComplete")}
            </div>
            <p className="mt-2 text-sm text-slate-600 dark:text-slate-300">
              {t("manage.createdCount", { count: importResult.createdCount })} ·{" "}
              {t("manage.skippedCount", { count: importResult.skippedCount })}
            </p>
            {importResult.errors.length > 0 && (
              <ul className="mt-3 max-h-40 space-y-1 overflow-y-auto text-sm text-amber-700 dark:text-amber-300">
                {importResult.errors.map((msg) => (
                  <li key={msg}>• {msg}</li>
                ))}
              </ul>
            )}
          </div>
        )}

        <button
          type="button"
          disabled={!selectedFile || importPending}
          onClick={() => void handleImport()}
          className="btn-primary"
        >
          {importPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
          {importPending ? t("manage.importing") : t("manage.importRecipes")}
        </button>
      </section>

      <section className="rounded-xl border border-dashed border-slate-300 p-4 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">
        <p className="font-medium text-slate-700 dark:text-slate-200">{t("manage.excelFormatTitle")}</p>
        <ul className="mt-2 list-inside list-disc space-y-1">
          <li>{t("manage.excelRecipesSheet")}</li>
          <li>{t("manage.excelIngredientsSheet")}</li>
          <li>{t("manage.excelStepsSheet")}</li>
        </ul>
        <p className="mt-2">{t("manage.duplicateSkipped")}</p>
      </section>
    </div>
  );
}
