"use client";

import { useState, useCallback, useRef } from "react";
import {
  X,
  Upload,
  Download,
  FileSpreadsheet,
  AlertCircle,
  CheckCircle2,
  Loader2,
  Trash2,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { Lang } from "@/lib/config";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

type EntityType = "properties" | "brokers" | "viewings" | "tenant_issues";
type ModalView = "upload" | "preview" | "results";

interface EntityConfig {
  templateUrl: string;
  importUrl: string;
  requiredFields: string[];
  allFields: string[];
  bodyKey: string;
  labelEn: string;
  labelAr: string;
}

interface ImportResult {
  imported: number;
  errors: string[];
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

const ENTITY_CONFIG: Record<EntityType, EntityConfig> = {
  properties: {
    templateUrl: "/api/real-estate/properties/template",
    importUrl: "/api/real-estate/properties/import",
    requiredFields: ["titleen", "propertytype", "listingtype", "city", "price"],
    allFields: [
      "titleen",
      "titlear",
      "propertytype",
      "listingtype",
      "city",
      "district",
      "price",
      "currency",
      "bedrooms",
      "bathrooms",
      "builtuparea",
      "furnishing",
      "ownership",
    ],
    bodyKey: "properties",
    labelEn: "Properties",
    labelAr: "العقارات",
  },
  brokers: {
    templateUrl: "/api/real-estate/brokers/template",
    importUrl: "/api/real-estate/brokers/import",
    requiredFields: ["nameen", "phone"],
    allFields: [
      "nameen",
      "namear",
      "phone",
      "email",
      "whatsappnumber",
      "licensenumber",
      "workstarttime",
      "workendtime",
      "maxviewingsperday",
    ],
    bodyKey: "brokers",
    labelEn: "Brokers",
    labelAr: "الوسطاء",
  },
  viewings: {
    templateUrl: "/api/real-estate/viewings/template",
    importUrl: "/api/real-estate/viewings/import",
    requiredFields: [
      "propertyid",
      "clientname",
      "clientphone",
      "viewingdate",
      "viewingtime",
    ],
    allFields: [
      "propertyid",
      "clientname",
      "clientphone",
      "clientemail",
      "viewingtype",
      "viewingdate",
      "viewingtime",
      "duration",
    ],
    bodyKey: "viewings",
    labelEn: "Viewings",
    labelAr: "المعاينات",
  },
  tenant_issues: {
    templateUrl: "/api/dashboard/tenant-issues/template",
    importUrl: "/api/dashboard/tenant-issues/import",
    requiredFields: ["propertyid", "title"],
    allFields: [
      "propertyid",
      "title",
      "description",
      "category",
      "priority",
      "unit",
      "tenantname",
    ],
    bodyKey: "issues",
    labelEn: "Tenant Issues",
    labelAr: "مشاكل المستأجرين",
  },
};

const ALL_ENTITY_TYPES: EntityType[] = [
  "properties",
  "brokers",
  "viewings",
  "tenant_issues",
];

// Header name → camelCase field mapping
const HEADER_MAP: Record<string, string> = {
  titleen: "titleEn",
  titlear: "titleAr",
  propertytype: "propertyType",
  listingtype: "listingType",
  builtuparea: "builtUpArea",
  nameen: "nameEn",
  namear: "nameAr",
  whatsappnumber: "whatsappNumber",
  licensenumber: "licenseNumber",
  workstarttime: "workStartTime",
  workendtime: "workEndTime",
  maxviewingsperday: "maxViewingsPerDay",
  propertyid: "propertyId",
  clientname: "clientName",
  clientphone: "clientPhone",
  clientemail: "clientEmail",
  viewingtype: "viewingType",
  viewingdate: "viewingDate",
  viewingtime: "viewingTime",
  tenantname: "tenantName",
};

// ---------------------------------------------------------------------------
// CSV Parsing (reused from FleetManagerModal pattern)
// ---------------------------------------------------------------------------

function parseCSVLine(line: string): string[] {
  const result: string[] = [];
  let current = "";
  let inQuotes = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') {
      if (inQuotes && i + 1 < line.length && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        inQuotes = !inQuotes;
      }
    } else if (ch === "," && !inQuotes) {
      result.push(current.trim());
      current = "";
    } else {
      current += ch;
    }
  }
  result.push(current.trim());
  return result;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

interface RealEstateBulkImportModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onImportComplete?: () => void;
  initialEntityType?: EntityType;
}

export default function RealEstateBulkImportModal({
  lang,
  isOpen,
  onClose,
  onImportComplete,
  initialEntityType = "properties",
}: RealEstateBulkImportModalProps) {
  const isAr = lang === "ar";
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [entityType, setEntityType] = useState<EntityType>(initialEntityType);
  const [view, setView] = useState<ModalView>("upload");
  const [parsedRows, setParsedRows] = useState<Record<string, string>[]>([]);
  const [headers, setHeaders] = useState<string[]>([]);
  const [importing, setImporting] = useState(false);
  const [result, setResult] = useState<ImportResult | null>(null);
  const [parseError, setParseError] = useState("");

  const config = ENTITY_CONFIG[entityType];

  // -----------------------------------------------------------------------
  // Reset
  // -----------------------------------------------------------------------

  const resetState = useCallback(() => {
    setView("upload");
    setParsedRows([]);
    setHeaders([]);
    setResult(null);
    setParseError("");
    setImporting(false);
    if (fileInputRef.current) fileInputRef.current.value = "";
  }, []);

  const handleEntityChange = useCallback(
    (type: EntityType) => {
      setEntityType(type);
      resetState();
    },
    [resetState],
  );

  // -----------------------------------------------------------------------
  // Template download
  // -----------------------------------------------------------------------

  const handleDownloadTemplate = useCallback(() => {
    window.open(config.templateUrl, "_blank");
  }, [config.templateUrl]);

  // -----------------------------------------------------------------------
  // CSV file handling
  // -----------------------------------------------------------------------

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

      const reader = new FileReader();
      reader.onload = (evt) => {
        const text = evt.target?.result as string;
        if (!text) {
          setParseError(isAr ? "الملف فارغ" : "File is empty");
          return;
        }

        const lines = text
          .split("\n")
          .map((l) => l.replace(/\r$/, ""))
          .filter((l) => l.trim().length > 0);

        if (lines.length < 2) {
          setParseError(
            isAr
              ? "الملف يجب أن يحتوي على رأس وصف واحد على الأقل"
              : "File must contain a header row and at least one data row",
          );
          return;
        }

        const rawHeaders = parseCSVLine(lines[0]);
        const normalizedHeaders = rawHeaders.map((h) =>
          h.toLowerCase().replace(/[^a-z]/g, ""),
        );

        // Verify required fields
        const missing = config.requiredFields.filter(
          (rf) => !normalizedHeaders.includes(rf),
        );
        if (missing.length > 0) {
          const fieldNames = missing
            .map((f) => HEADER_MAP[f] || f)
            .join(", ");
          setParseError(
            isAr
              ? `أعمدة مطلوبة مفقودة: ${fieldNames}`
              : `Missing required columns: ${fieldNames}`,
          );
          return;
        }

        // Parse data rows
        const rows: Record<string, string>[] = [];
        for (let i = 1; i < lines.length; i++) {
          const cells = parseCSVLine(lines[i]);
          const row: Record<string, string> = {};
          normalizedHeaders.forEach((h, idx) => {
            const fieldName = HEADER_MAP[h] || h;
            row[fieldName] = cells[idx] || "";
          });
          rows.push(row);
        }

        // Use camelCase headers for display
        const displayHeaders = normalizedHeaders.map(
          (h) => HEADER_MAP[h] || h,
        );

        setHeaders(displayHeaders);
        setParsedRows(rows);
        setView("preview");
      };
      reader.readAsText(file);
    },
    [config.requiredFields, isAr],
  );

  // -----------------------------------------------------------------------
  // Remove row
  // -----------------------------------------------------------------------

  const handleRemoveRow = useCallback((index: number) => {
    setParsedRows((prev) => prev.filter((_, i) => i !== index));
  }, []);

  // -----------------------------------------------------------------------
  // Import
  // -----------------------------------------------------------------------

  const handleImport = useCallback(async () => {
    if (parsedRows.length === 0) return;
    setImporting(true);

    try {
      const res = await fetchWithCSRF(config.importUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [config.bodyKey]: parsedRows }),
      });

      const data = await res.json();
      setResult({
        imported: data.imported ?? 0,
        errors: data.errors ?? [],
      });
      setView("results");

      if (data.imported > 0 && onImportComplete) {
        onImportComplete();
      }
    } catch {
      setResult({
        imported: 0,
        errors: [isAr ? "فشل الاتصال بالخادم" : "Failed to connect to server"],
      });
      setView("results");
    } finally {
      setImporting(false);
    }
  }, [parsedRows, config, onImportComplete, isAr]);

  // -----------------------------------------------------------------------
  // Render
  // -----------------------------------------------------------------------

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
      <div
        className="w-full max-w-3xl max-h-[85vh] flex flex-col rounded-2xl bg-white shadow-xl"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-100 px-6 py-4 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center">
              <FileSpreadsheet className="w-5 h-5 text-blue-600" />
            </div>
            <h3 className="text-lg font-bold text-slate-900">
              {isAr ? "استيراد بيانات" : "Bulk Import"}
            </h3>
          </div>
          <button
            onClick={() => {
              resetState();
              onClose();
            }}
            className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Entity type tabs */}
        <div className="flex gap-1 px-6 pt-4 shrink-0">
          {ALL_ENTITY_TYPES.map((type) => {
            const c = ENTITY_CONFIG[type];
            return (
              <button
                key={type}
                onClick={() => handleEntityChange(type)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  entityType === type
                    ? "bg-slate-900 text-white"
                    : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                }`}
              >
                {isAr ? c.labelAr : c.labelEn}
              </button>
            );
          })}
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-6 py-5">
          {/* Upload View */}
          {view === "upload" && (
            <div className="space-y-5">
              {/* Template download */}
              <div className="flex items-center justify-between rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4">
                <div>
                  <p className="text-sm font-medium text-slate-700">
                    {isAr ? "1. حمّل القالب" : "1. Download template"}
                  </p>
                  <p className="text-xs text-slate-500 mt-0.5">
                    {isAr
                      ? "قم بتعبئة الحقول المطلوبة في ملف CSV"
                      : "Fill in the required fields in the CSV file"}
                  </p>
                </div>
                <button
                  onClick={handleDownloadTemplate}
                  className="inline-flex items-center gap-2 rounded-lg bg-white border border-slate-200 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
                >
                  <Download className="w-4 h-4" />
                  {isAr ? "تحميل" : "Download"}
                </button>
              </div>

              {/* File upload */}
              <div>
                <p className="text-sm font-medium text-slate-700 mb-2">
                  {isAr ? "2. ارفع الملف المكتمل" : "2. Upload completed file"}
                </p>
                <label className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-slate-300 bg-white p-8 cursor-pointer hover:border-slate-400 hover:bg-slate-50 transition-colors">
                  <Upload className="w-8 h-8 text-slate-400 mb-2" />
                  <span className="text-sm font-medium text-slate-600">
                    {isAr ? "اختر ملف CSV" : "Choose CSV file"}
                  </span>
                  <span className="text-xs text-slate-400 mt-1">
                    {isAr ? "أو اسحب وأفلت هنا" : "or drag and drop here"}
                  </span>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".csv"
                    onChange={handleFileSelect}
                    className="hidden"
                  />
                </label>
              </div>

              {parseError && (
                <div className="flex items-start gap-2 rounded-lg bg-red-50 border border-red-200 p-3">
                  <AlertCircle className="w-4 h-4 text-red-500 mt-0.5 shrink-0" />
                  <p className="text-sm text-red-700">{parseError}</p>
                </div>
              )}

              {/* Required fields hint */}
              <div className="text-xs text-slate-400">
                <span className="font-medium">
                  {isAr ? "الحقول المطلوبة:" : "Required fields:"}
                </span>{" "}
                {config.requiredFields
                  .map((f) => HEADER_MAP[f] || f)
                  .join(", ")}
              </div>
            </div>
          )}

          {/* Preview View */}
          {view === "preview" && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <p className="text-sm font-medium text-slate-700">
                  {isAr
                    ? `${parsedRows.length} صف جاهز للاستيراد`
                    : `${parsedRows.length} rows ready to import`}
                </p>
                <button
                  onClick={resetState}
                  className="text-sm text-slate-500 hover:text-slate-700"
                >
                  {isAr ? "إعادة الرفع" : "Re-upload"}
                </button>
              </div>

              <div className="overflow-x-auto rounded-lg border border-gray-200">
                <table className="min-w-full text-xs">
                  <thead className="bg-slate-50">
                    <tr>
                      <th className="px-3 py-2 text-left font-medium text-slate-500">
                        #
                      </th>
                      {headers.slice(0, 6).map((h) => (
                        <th
                          key={h}
                          className="px-3 py-2 text-left font-medium text-slate-500"
                        >
                          {h}
                        </th>
                      ))}
                      <th className="px-3 py-2" />
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {parsedRows.map((row, i) => (
                      <tr key={i} className="hover:bg-slate-50">
                        <td className="px-3 py-2 text-slate-400">{i + 1}</td>
                        {headers.slice(0, 6).map((h) => (
                          <td
                            key={h}
                            className="px-3 py-2 text-slate-700 max-w-[150px] truncate"
                          >
                            {row[h] || "—"}
                          </td>
                        ))}
                        <td className="px-3 py-2">
                          <button
                            onClick={() => handleRemoveRow(i)}
                            className="text-slate-400 hover:text-red-500 transition-colors"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {parsedRows.length === 0 && (
                <p className="text-center text-sm text-slate-400 py-4">
                  {isAr ? "لا توجد صفوف" : "No rows remaining"}
                </p>
              )}
            </div>
          )}

          {/* Results View */}
          {view === "results" && result && (
            <div className="space-y-4">
              {result.imported > 0 && (
                <div className="flex items-center gap-3 rounded-xl bg-green-50 border border-green-200 p-4">
                  <CheckCircle2 className="w-6 h-6 text-green-600 shrink-0" />
                  <div>
                    <p className="text-sm font-semibold text-green-800">
                      {isAr
                        ? `تم استيراد ${result.imported} بنجاح`
                        : `${result.imported} imported successfully`}
                    </p>
                  </div>
                </div>
              )}

              {result.errors.length > 0 && (
                <div className="rounded-xl bg-red-50 border border-red-200 p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <AlertCircle className="w-5 h-5 text-red-600 shrink-0" />
                    <p className="text-sm font-semibold text-red-800">
                      {isAr
                        ? `${result.errors.length} أخطاء`
                        : `${result.errors.length} errors`}
                    </p>
                  </div>
                  <ul className="space-y-1 max-h-48 overflow-y-auto">
                    {result.errors.map((err, i) => (
                      <li key={i} className="text-xs text-red-700">
                        {err}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 border-t border-gray-100 px-6 py-4 shrink-0">
          {view === "preview" && (
            <>
              <button
                onClick={resetState}
                className="rounded-xl px-4 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-100 transition-colors"
              >
                {isAr ? "رجوع" : "Back"}
              </button>
              <button
                onClick={handleImport}
                disabled={importing || parsedRows.length === 0}
                className="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {importing ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {isAr ? "جارٍ الاستيراد..." : "Importing..."}
                  </>
                ) : isAr ? (
                  `استيراد ${parsedRows.length} صف`
                ) : (
                  `Import ${parsedRows.length} rows`
                )}
              </button>
            </>
          )}
          {view === "results" && (
            <button
              onClick={() => {
                resetState();
                onClose();
              }}
              className="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-medium text-white hover:bg-slate-800 transition-colors"
            >
              {isAr ? "تم" : "Done"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
