"use client";

import { useState, useRef, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Upload, FileText, AlertTriangle, X, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { parseVCard, detectDuplicates } from "@/lib/vcard";
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
import { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
import {
  parseCSV,
  autoMapColumns,
  mapRowToContact,
  detectDuplicatesByEmail,
  type CsvColumnMapping,
  type CsvParseResult,
} from "@/lib/contact-csv-import";

type FileType = "vcf" | "csv" | null;

interface ContactImportDialogProps {
  existingContacts: ContactCard[];
  addressBooks?: AddressBook[];
  onImport: (contacts: ContactCard[]) => Promise<number>;
  onClose: () => void;
}

export function ContactImportDialog({
  existingContacts,
  addressBooks,
  onImport,
  onClose,
}: ContactImportDialogProps) {
  const t = useTranslations("contacts");
  const fileRef = useRef<HTMLInputElement>(null);
  const [fileType, setFileType] = useState<FileType>(null);
  const [parsed, setParsed] = useState<ContactCard[]>([]);
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [duplicates, setDuplicates] = useState<Map<number, string>>(new Map());
  const [isImporting, setIsImporting] = useState(false);
  const [result, setResult] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  const [csvData, setCsvData] = useState<CsvParseResult | null>(null);
  const [mapping, setMapping] = useState<CsvColumnMapping | null>(null);
  const [targetBookId, setTargetBookId] = useState("");
  const [showPreview, setShowPreview] = useState(false);

  const ALLOWED_ACCEPT = ".vcf,.vcard,.csv,text/csv,text/vcard";

  const books = addressBooks || [];
  const defaultBookId =
    books.find((b) => b.isDefault)?.id || books[0]?.id || "";
  const effectiveBookId = targetBookId || defaultBookId;
  const bookOptions = books.map((b) => ({
    value: b.id,
    label: b.name,
  }));

  const handleFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setError(null);
    setResult(null);
    setFileType(null);
    setParsed([]);
    setSelected(new Set());
    setDuplicates(new Map());
    setCsvData(null);
    setMapping(null);
    setShowPreview(false);
    setTargetBookId("");

    if (file.size > 10 * 1024 * 1024) {
      setError(t("import.file_too_large"));
      return;
    }

    const name = file.name.toLowerCase();

    try {
      if (name.endsWith(".csv") || file.type === "text/csv") {
        setFileType("csv");
        const text = await file.text();
        const result = parseCSV(text);

        if (result.rows.length === 0) {
          setError(t("import.no_contacts"));
          return;
        }

        setCsvData(result);
        setMapping(autoMapColumns(result.headers));
        setTargetBookId(defaultBookId);
      } else {
        setFileType("vcf");
        const text = await file.text();
        const contacts = parseVCard(text);

        if (contacts.length === 0) {
          setError(t("import.no_contacts"));
          return;
        }

        const dupes = detectDuplicates(existingContacts, contacts);
        setParsed(contacts);
        setDuplicates(dupes);

        const initialSelected = new Set<number>();
        contacts.forEach((_, idx) => {
          if (!dupes.has(idx)) initialSelected.add(idx);
        });
        setSelected(initialSelected);
      }
    } catch (err) {
      console.error("Failed to parse file:", err);
      setError(t("import.parse_error"));
    }
  }, [existingContacts, t, defaultBookId]);

  const applyCsvMapping = useCallback(() => {
    if (!csvData || !mapping) return;

    const bookIds = effectiveBookId ? { [effectiveBookId]: true } : {};
    const contacts: ContactCard[] = [];

    for (const row of csvData.rows) {
      const contact = mapRowToContact(row, mapping, bookIds);
      if (contact) contacts.push(contact);
    }

    if (contacts.length === 0) {
      setError(t("import.no_contacts"));
      return;
    }

    const dupes = detectDuplicatesByEmail(existingContacts, contacts);
    setParsed(contacts);
    setDuplicates(dupes);

    const initialSelected = new Set<number>();
    contacts.forEach((_, idx) => {
      if (!dupes.has(idx)) initialSelected.add(idx);
    });
    setSelected(initialSelected);
    setShowPreview(true);
  }, [csvData, mapping, effectiveBookId, existingContacts, t]);

  const toggleSelect = (idx: number) => {
    const next = new Set(selected);
    if (next.has(idx)) {
      next.delete(idx);
    } else {
      next.add(idx);
    }
    setSelected(next);
  };

  const selectAll = () => {
    setSelected(new Set(parsed.map((_, i) => i)));
  };

  const deselectAll = () => {
    setSelected(new Set());
  };

  const handleImport = async () => {
    const toImport = parsed.filter((_, i) => selected.has(i));
    if (toImport.length === 0) return;

    setIsImporting(true);
    try {
      const count = await onImport(toImport);
      setResult(count);
    } catch (err) {
      console.error("Failed to import contacts:", err);
      setError(t("import.failed"));
    } finally {
      setIsImporting(false);
    }
  };

  const renderCsvMapping = () => {
    if (!csvData || !mapping) return null;

    const fields: Array<{ key: keyof CsvColumnMapping; label: string }> = [
      { key: "firstName", label: t("import.csv_first_name") },
      { key: "lastName", label: t("import.csv_last_name") },
      { key: "email", label: t("import.csv_email") },
      { key: "phone", label: t("import.csv_phone") },
      { key: "company", label: t("import.csv_company") },
      { key: "jobTitle", label: t("import.csv_job_title") },
      { key: "address", label: t("import.csv_address") },
      { key: "city", label: t("import.csv_city") },
      { key: "region", label: t("import.csv_region") },
      { key: "postcode", label: t("import.csv_postcode") },
      { key: "country", label: t("import.csv_country") },
      { key: "website", label: t("import.csv_website") },
      { key: "note", label: t("import.csv_note") },
      { key: "nickname", label: t("import.csv_nickname") },
    ];

    const headerOptions = csvData.headers.map((h, i) => ({
      value: String(i),
      label: h,
    }));

    return (
      <div className="space-y-3">
        <p className="text-sm font-medium">{t("import.csv_map_columns")}</p>
        <div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto">
          {fields.map(({ key, label }) => (
            <div key={key} className="flex items-center gap-2">
              <label className="text-xs text-muted-foreground w-24 flex-shrink-0 truncate">
                {label}
              </label>
              <select
                value={mapping[key] >= 0 ? String(mapping[key]) : "-1"}
                onChange={(e) => {
                  setMapping((prev) => prev ? {
                    ...prev,
                    [key]: parseInt(e.target.value, 10),
                  } : null);
                }}
                className="flex-1 px-2 py-1 text-xs rounded border border-border bg-muted text-foreground focus:outline-none focus:ring-1 focus:ring-ring"
                dir="auto"
              >
                <option value="-1">{t("import.csv_ignore")}</option>
                {headerOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          ))}
        </div>

        {books.length > 0 && (
          <div className="flex items-center gap-2 pt-2">
            <label className="text-xs text-muted-foreground flex-shrink-0">
              {t("import.csv_address_book")}
            </label>
            <select
              value={effectiveBookId}
              onChange={(e) => setTargetBookId(e.target.value)}
              className="px-2 py-1 text-xs rounded border border-border bg-muted text-foreground focus:outline-none focus:ring-1 focus:ring-ring"
              dir="auto"
            >
              {bookOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        )}

        <div className="flex gap-2 pt-1">
          <Button size="sm" onClick={applyCsvMapping}>
            {t("import.csv_preview")}
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setFileType(null);
              setCsvData(null);
              setMapping(null);
              if (fileRef.current) fileRef.current.value = "";
            }}
          >
            {t("form.cancel")}
          </Button>
        </div>
      </div>
    );
  };

  const renderCsvPreview = () => {
    if (!csvData || !mapping || !showPreview) return null;
    const previewRows = csvData.rows.slice(0, 5);

    return (
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-sm font-medium">{t("import.csv_preview_title", { count: parsed.length })}</p>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowPreview(false)}
          >
            {t("import.csv_back")}
          </Button>
        </div>
        <div className="border rounded-md overflow-x-auto">
          <table className="w-full text-xs">
            <thead>
              <tr className="bg-muted">
                {csvData.headers.map((h, i) => (
                  <th key={i} className="px-2 py-1.5 text-start font-medium text-muted-foreground whitespace-nowrap">
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {previewRows.map((row, ri) => (
                <tr key={ri} className="border-t border-border">
                  {row.map((cell, ci) => (
                    <td key={ci} className="px-2 py-1.5 truncate max-w-[150px]">
                      {cell}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="flex gap-2">
          <Button size="sm" onClick={applyCsvMapping}>
            {t("import.csv_load_all")}
          </Button>
        </div>
      </div>
    );
  };

  return (
    <div className="flex flex-col h-full">
      <div className="px-6 py-4 border-b border-border flex items-center justify-between">
        <h2 className="text-lg font-semibold">{t("import.title")}</h2>
        <Button variant="ghost" size="icon" onClick={onClose} className="h-8 w-8">
          <X className="w-4 h-4" />
        </Button>
      </div>

      <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
        {result !== null ? (
          <div className="flex flex-col items-center justify-center py-12">
            <div className="w-12 h-12 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mb-4">
              <Check className="w-6 h-6 text-green-600 dark:text-green-400" />
            </div>
            <p className="text-sm font-medium">{t("import.success", { count: result })}</p>
            <Button variant="outline" size="sm" onClick={onClose} className="mt-4">
              {t("import.close")}
            </Button>
          </div>
        ) : fileType === null ? (
          <>
            <input
              ref={fileRef}
              type="file"
              accept={ALLOWED_ACCEPT}
              onChange={handleFileChange}
              className="hidden"
            />

            <button
              type="button"
              onClick={() => fileRef.current?.click()}
              className={cn(
                "w-full border-2 border-dashed rounded-lg py-12 px-4",
                "flex flex-col items-center gap-3 transition-colors",
                "hover:border-primary hover:bg-primary/5",
                "text-muted-foreground"
              )}
            >
              <Upload className="w-8 h-8" />
              <p className="text-sm font-medium">{t("import.drop_hint")}</p>
              <p className="text-xs">{t("import.file_types_csv")}</p>
            </button>

            {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>
            )}
          </>
        ) : fileType === "csv" && csvData && !showPreview ? (
          renderCsvMapping()
        ) : fileType === "csv" && csvData && showPreview ? (
          renderCsvPreview()
        ) : (
          <>
            {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>
            )}

            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                {t("import.found", { count: parsed.length })}
              </p>
              <div className="flex gap-2">
                <Button variant="ghost" size="sm" onClick={selectAll}>
                  {t("import.select_all")}
                </Button>
                <Button variant="ghost" size="sm" onClick={deselectAll}>
                  {t("import.deselect_all")}
                </Button>
              </div>
            </div>

            <div className="border rounded-md divide-y divide-border max-h-96 overflow-y-auto">
              {parsed.map((contact, idx) => {
                const cName = getContactDisplayName(contact);
                const cEmail = getContactPrimaryEmail(contact);
                const isDupe = duplicates.has(idx);
                const isSelected = selected.has(idx);

                return (
                  <button
                    key={idx}
                    type="button"
                    onClick={() => toggleSelect(idx)}
                    className={cn(
                      "w-full flex items-center gap-3 px-3 py-2.5 text-start transition-colors hover:bg-muted",
                      isSelected && "bg-primary/5"
                    )}
                  >
                    <div className={cn(
                      "w-5 h-5 rounded border flex items-center justify-center flex-shrink-0 transition-colors",
                      isSelected ? "bg-primary border-primary text-primary-foreground" : "border-border"
                    )}>
                      {isSelected && <Check className="w-3 h-3" />}
                    </div>
                    <FileText className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium truncate">{cName || cEmail || "-"}</div>
                      {cEmail && cName && (
                        <div className="text-xs text-muted-foreground truncate">{cEmail}</div>
                      )}
                    </div>
                    {isDupe && (
                      <span className="text-xs px-1.5 py-0.5 rounded bg-warning/15 text-warning flex-shrink-0">
                        {t("import.duplicate")}
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
          </>
        )}
      </div>

      {parsed.length > 0 && result === null && fileType !== "csv" && (
        <div className="flex items-center justify-between px-6 py-4 border-t border-border">
          <p className="text-sm text-muted-foreground">
            {t("import.selected", { count: selected.size })}
          </p>
          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose} disabled={isImporting}>
              {t("form.cancel")}
            </Button>
            <Button onClick={handleImport} disabled={isImporting || selected.size === 0}>
              {isImporting ? t("import.importing") : t("import.import_button")}
            </Button>
          </div>
        </div>
      )}

      {fileType === "csv" && showPreview && parsed.length > 0 && result === null && (
        <div className="flex items-center justify-between px-6 py-4 border-t border-border">
          <p className="text-sm text-muted-foreground">
            {t("import.selected", { count: selected.size })}
          </p>
          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose} disabled={isImporting}>
              {t("form.cancel")}
            </Button>
            <Button onClick={handleImport} disabled={isImporting || selected.size === 0}>
              {isImporting ? t("import.importing") : t("import.import_button")}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
