"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  TableCellsIcon,
  ArrowsRightLeftIcon,
} from "@heroicons/react/24/outline";
import { useSetColumnMapping } from "@/lib/bulkUpload/client";
import {
  ADDRESS_FIELDS,
  CLASSIFIER_FIELDS,
  NOT_PROVIDED,
  buildInitialMapping,
  validateColumnMapping,
  type InternalField,
} from "@/lib/bulkUpload/columnFields";

interface Props {
  portfolioId: string;
  uploadId: string;
  filename: string;
  sourceHeaders: string[];
  existingMapping?: Record<string, string>;
}

export default function MapColumnsClient({
  portfolioId,
  uploadId,
  filename,
  sourceHeaders,
  existingMapping,
}: Props) {
  const router = useRouter();
  // mapping: internal field → source CSV header. Unmapped fields are absent.
  const [mapping, setMapping] = useState<Record<string, string>>(
    buildInitialMapping(sourceHeaders, existingMapping)
  );
  const setMappingMutation = useSetColumnMapping(portfolioId, uploadId);

  const validationError = validateColumnMapping(mapping);
  const submitting = setMappingMutation.isPending;
  const requestError = setMappingMutation.error?.message ?? null;
  const canSubmit = validationError === null && !submitting;

  function setField(field: string, header: string) {
    setMapping((prev) => {
      const next = { ...prev };
      if (header === NOT_PROVIDED) delete next[field];
      else next[field] = header;
      return next;
    });
  }

  function handleSubmit() {
    if (!canSubmit) return;
    setMappingMutation.mutate(
      { columnMapping: mapping },
      {
        onSuccess: () => {
          router.push(`/portfolio/${portfolioId}/bulk-upload/${uploadId}`);
        },
      }
    );
  }

  function renderRow(field: InternalField) {
    const value = mapping[field.value] ?? NOT_PROVIDED;
    const isMapped = value !== NOT_PROVIDED;
    return (
      <div
        key={field.value}
        className="grid grid-cols-12 items-center px-6 py-4 hover:bg-gray-50/50 transition-colors"
      >
        {/* Internal field */}
        <div className="col-span-4 flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center shrink-0">
            <TableCellsIcon className="h-4 w-4 text-gray-400" />
          </div>
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {field.label}
              {field.required && <span className="text-amber-600"> *</span>}
            </p>
            <p className="text-xs text-gray-400">
              {field.kind === "classifier" ? "Landlord description" : "Internal field"}
            </p>
          </div>
        </div>

        {/* Arrow */}
        <div className="col-span-1 flex justify-center">
          <ArrowsRightLeftIcon className="h-4 w-4 text-gray-300" />
        </div>

        {/* Header picker */}
        <div className="col-span-5">
          <select
            value={value}
            onChange={(e) => setField(field.value, e.target.value)}
            className="w-full text-sm border border-gray-200 rounded-lg px-3 py-2 bg-white text-gray-800 focus:outline-none focus:ring-2 focus:ring-[#14163d]/20 focus:border-[#14163d]"
          >
            <option value={NOT_PROVIDED}>Not provided</option>
            {sourceHeaders.map((header, index) => (
              <option key={`${header}-${index}`} value={header}>
                {header}
              </option>
            ))}
          </select>
        </div>

        {/* Status badge */}
        <div className="col-span-2 flex justify-end">
          <span
            className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold ${
              isMapped ? "bg-amber-50 text-amber-700" : "bg-gray-100 text-gray-400"
            }`}
          >
            <span className="w-1.5 h-1.5 rounded-full bg-current opacity-70" />
            {isMapped ? "Mapped" : "Not provided"}
          </span>
        </div>
      </div>
    );
  }

  function renderSection(title: string, subtitle: string, fields: InternalField[]) {
    return (
      <div className="bg-white border border-gray-100 rounded-2xl overflow-hidden shadow-sm mb-6">
        <div className="px-6 py-3 bg-gray-50 border-b border-gray-100">
          <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
            {title}
          </p>
          <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>
        </div>
        {sourceHeaders.length === 0 ? (
          <div className="px-6 py-12 text-center text-sm text-gray-400">
            No headers found in this file.
          </div>
        ) : (
          <div className="divide-y divide-gray-50">{fields.map(renderRow)}</div>
        )}
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-6 py-10">
      {/* Breadcrumb + step */}
      <div className="flex items-center justify-between mb-2">
        <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest">
          Bulk Uploads › Column Remapper
        </p>
        <div className="flex items-center gap-1.5">
          <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
            Step 2 of 3
          </span>
          <div className="flex gap-1 ml-2">
            {[1, 2, 3].map((s) => (
              <div
                key={s}
                className={`h-1.5 rounded-full ${
                  s <= 2 ? "w-8 bg-[#14163d]" : "w-8 bg-gray-200"
                }`}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight mb-1">
          Column Remapper
        </h1>
        <p className="text-sm text-gray-500 max-w-lg">
          Tell us which spreadsheet column feeds each field. Address fields drive
          matching; landlord-description fields are classified into property facts.
        </p>
      </div>

      {renderSection(
        "Address fields",
        "Used for address matching. A column can feed only one address field.",
        ADDRESS_FIELDS
      )}
      {renderSection(
        "Landlord description fields (optional)",
        "Classified into property facts. Several fields may share one column.",
        CLASSIFIER_FIELDS
      )}

      {/* Validation / request error */}
      {validationError && (
        <p className="text-xs text-amber-600 mb-4">{validationError}</p>
      )}
      {requestError && <p className="text-xs text-red-500 mb-4">{requestError}</p>}

      {/* Footer */}
      <div className="flex items-center justify-between">
        <Link
          href={`/portfolio/${portfolioId}/bulk-upload`}
          className="flex items-center gap-1.5 text-sm font-semibold text-gray-400 hover:text-gray-700 transition-colors"
        >
          <ArrowLeftIcon className="h-4 w-4" />
          Back
        </Link>

        <div className="flex items-center gap-3">
          <Link
            href={`/portfolio/${portfolioId}/bulk-upload`}
            className="text-sm font-semibold text-gray-400 hover:text-gray-700 transition-colors"
          >
            Cancel
          </Link>
          <button
            onClick={handleSubmit}
            disabled={!canSubmit}
            className={`flex items-center gap-2 px-7 py-2.5 rounded-2xl bg-gradient-to-br from-[#14163d] to-[#15173e] text-white text-sm font-bold transition-opacity ${
              canSubmit ? "opacity-100 hover:opacity-90" : "opacity-40 cursor-not-allowed"
            }`}
          >
            {submitting ? "Saving…" : "Process Mapping"}
            {!submitting && <ArrowRightIcon className="h-4 w-4" />}
          </button>
        </div>
      </div>

      {/* Pro tip */}
      <div className="mt-10 bg-gray-50 rounded-2xl p-6">
        <p className="text-xs font-semibold text-midblue uppercase tracking-wider mb-2">
          Pro Tip
        </p>
        <p className="text-sm text-gray-500 italic">
          &ldquo;Fields left as &ldquo;Not provided&rdquo; are ignored. The same
          column can feed several landlord-description fields — e.g. one
          &ldquo;Property Type&rdquo; column can drive both Property Type and Built
          Form.&rdquo;
        </p>
      </div>
    </div>
  );
}
