"use client";

import { useState, useRef, useCallback, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Upload, AlertTriangle, Check, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { SettingsSection, SettingItem, RadioGroup, Select } from "./settings-section";
import { importEmails, type ConflictResolution, type ImportProgress, type ImportResult } from "@/lib/email-import";
import { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { EML_IMPORT_ACCEPT } from "@/lib/eml-import";
import { toast } from "@/stores/toast-store";
import { cn } from "@/lib/utils";

export function ImportSettings() {
  const t = useTranslations("settings.importer");
  const { client } = useAuthStore();
  const { mailboxes } = useEmailStore();
  const fileRef = useRef<HTMLInputElement>(null);
  const [files, setFiles] = useState<File[]>([]);
  const [destination, setDestination] = useState("");
  const [conflict, setConflict] = useState<ConflictResolution>("skip");
  const [progress, setProgress] = useState<ImportProgress | null>(null);
  const [result, setResult] = useState<ImportResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [importing, setImporting] = useState(false);
  const abortRef = useRef<AbortController | null>(null);

  useEffect(() => {
    if (mailboxes.length > 0 && !destination) {
      const inbox = mailboxes.find((m) => m.role === "inbox") || mailboxes[0];
      if (inbox) setDestination(inbox.id);
    }
  }, [mailboxes, destination]);

  const folderOptions = mailboxes.map((m) => ({
    value: m.id,
    label: m.name,
  }));

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files;
    if (!selected || selected.length === 0) return;
    setError(null);
    setResult(null);
    setProgress(null);
    setFiles(Array.from(selected));
  }, []);

  const handleImport = useCallback(async () => {
    if (!client || files.length === 0 || !destination) return;

    setImporting(true);
    setError(null);
    setResult(null);
    const controller = new AbortController();
    abortRef.current = controller;

    try {
      const res = await importEmails({
        client,
        files,
        destinationMailboxId: destination,
        conflictResolution: conflict,
        onProgress: (p) => setProgress({ ...p }),
        signal: controller.signal,
      });
      setResult(res);
      if (res.imported > 0) {
        toast.success(t("success", { count: res.imported }));
      }
    } catch (err) {
      if (!controller.signal.aborted) {
        const msg = err instanceof Error ? err.message : t("fail");
        setError(msg);
        toast.error(msg);
      }
    } finally {
      setImporting(false);
      abortRef.current = null;
    }
  }, [client, files, destination, conflict, t]);

  const handleCancel = () => {
    abortRef.current?.abort();
    setImporting(false);
  };

  const reset = () => {
    setFiles([]);
    setResult(null);
    setProgress(null);
    setError(null);
    if (fileRef.current) fileRef.current.value = "";
  };

  const progressPercent = progress && progress.total > 0
    ? Math.round((progress.processed / progress.total) * 100)
    : 0;

  return (
    <SettingsSection
      title={t("title")}
      description={t("description")}
    >
      <SettingItem
        label={t("file_label")}
        description={t("file_description")}
      >
        <div className="flex items-center gap-2">
          <input
            ref={fileRef}
            type="file"
            accept={EML_IMPORT_ACCEPT}
            multiple
            onChange={handleFileChange}
            className="hidden"
          />
          <Button
            variant="outline"
            size="sm"
            onClick={() => fileRef.current?.click()}
            disabled={importing}
          >
            <Upload className="w-4 h-4 me-2" />
            {files.length > 0
              ? t("files_selected", { count: files.length })
              : t("choose_files")}
          </Button>
          {files.length > 0 && !importing && (
            <Button variant="ghost" size="sm" onClick={reset} aria-label="Clear selection">
              <X className="w-4 h-4" />
            </Button>
          )}
        </div>
      </SettingItem>

      <SettingItem
        label={t("folder_label")}
        description={t("folder_description")}
      >
        <Select
          value={destination}
          onChange={setDestination}
          options={folderOptions}
          disabled={importing || folderOptions.length === 0}
        />
      </SettingItem>

      <SettingItem
        label={t("conflict_label")}
        description={t("conflict_description")}
      >
        <RadioGroup
          value={conflict}
          onChange={(v) => setConflict(v as ConflictResolution)}
          options={[
            { value: "skip", label: t("conflict_skip") },
            { value: "replace", label: t("conflict_replace") },
            { value: "copy", label: t("conflict_copy") },
          ]}
        />
      </SettingItem>

      {files.length > 0 && !result && (
        <SettingItem label={t("action_label")} description="">
          <Button
            onClick={handleImport}
            disabled={importing || !destination}
          >
            {importing ? t("importing") : t("start_import", { count: files.length })}
          </Button>
        </SettingItem>
      )}

      {error && (
        <div className="text-sm text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950 px-3 py-2 rounded flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 flex-shrink-0" />
          {error}
        </div>
      )}

      {progress && importing && (
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm text-muted-foreground">
            <span>{progress.currentFile}</span>
            <span>{progressPercent}%</span>
          </div>
          <div className="w-full bg-muted rounded-full h-2">
            <div
              className="bg-primary h-2 rounded-full transition-all duration-300"
              style={{ width: `${progressPercent}%` }}
            />
          </div>
          <div className="flex justify-between text-xs text-muted-foreground">
            <span>{t("progress_imported", { count: progress.imported })}</span>
            <span>{t("progress_skipped", { count: progress.skipped })}</span>
            <span>{t("progress_failed", { count: progress.failed })}</span>
          </div>
          <div className="flex justify-center">
            <Button variant="outline" size="sm" onClick={handleCancel}>
              {t("cancel")}
            </Button>
          </div>
        </div>
      )}

      {result && !importing && (
        <div className={cn(
          "rounded-lg p-4 space-y-3",
          result.failed > 0
            ? "bg-warning/10 border border-warning/30"
            : "bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800"
        )}>
          <div className="flex items-center gap-2">
            <Check className="w-5 h-5 text-green-600 dark:text-green-400" />
            <span className="font-medium text-sm">{t("import_complete")}</span>
          </div>
          <div className="text-sm space-y-1">
            <p>{t("summary_imported", { count: result.imported })}</p>
            <p>{t("summary_skipped", { count: result.skipped })}</p>
            <p>{t("summary_failed", { count: result.failed })}</p>
          </div>
          {result.errors.length > 0 && (
            <details className="text-xs">
              <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
                {t("error_details", { count: result.errors.length })}
              </summary>
              <ul className="mt-2 space-y-1 ps-4 list-disc">
                {result.errors.map((e, i) => (
                  <li key={i} className="text-red-600 dark:text-red-400">
                    <span className="font-medium">{e.file}</span>: {e.error}
                  </li>
                ))}
              </ul>
            </details>
          )}
          <Button variant="outline" size="sm" onClick={reset}>
            {t("import_more")}
          </Button>
        </div>
      )}
    </SettingsSection>
  );
}
