// =============================================================================
// HeadlineSift.com — Source Mapping Add/Edit Form
// =============================================================================
"use client";

import { useFormState, useFormStatus } from "react-dom";
import { createSourceMapping, updateSourceMapping } from "./actions";

// ============================================================================
// Types
// ============================================================================

interface EditMappingInput {
  id: string;
  sourceId: string;
  countryId: string;
  categoryId: string;
  priority: number;
  status: string;
}

interface SourceOption {
  id: string;
  name: string;
  sourceType: string;
}

interface CountryOption {
  id: string;
  name: string;
  code: string;
}

interface CategoryOption {
  id: string;
  name: string;
  slug: string;
  level: string;
}

interface SourceMappingFormProps {
  editMapping?: EditMappingInput | null;
  sourceOptions: SourceOption[];
  countryOptions: CountryOption[];
  categoryOptions: CategoryOption[];
  onCancel: () => void;
}

// ============================================================================
// Submit Button
// ============================================================================

function SubmitButton({ isEditing }: { isEditing: boolean }) {
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending} className="btn-primary">
      {pending ? (
        <span className="flex items-center gap-2">
          <svg
            className="h-4 w-4 animate-spin"
            viewBox="0 0 24 24"
            fill="none"
          >
            <circle
              className="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              strokeWidth="4"
            />
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
            />
          </svg>
          {isEditing ? "Saving…" : "Creating…"}
        </span>
      ) : isEditing ? (
        "Save Changes"
      ) : (
        "Create Mapping"
      )}
    </button>
  );
}

// ============================================================================
// Form Component
// ============================================================================

export default function SourceMappingForm({
  editMapping,
  sourceOptions,
  countryOptions,
  categoryOptions,
  onCancel,
}: SourceMappingFormProps) {
  const isEditing = !!editMapping;

  const action = editMapping
    ? updateSourceMapping.bind(null, editMapping.id)
    : createSourceMapping;

  const [state, formAction] = useFormState(action, {
    error: undefined,
    success: undefined,
  });

  return (
    <div className="card animate-slide-up">
      <div className="flex items-center justify-between mb-5">
        <h2 className="text-lg font-semibold text-heading">
          {isEditing ? "Edit Source Mapping" : "Add Source Mapping"}
        </h2>
        <button
          type="button"
          onClick={onCancel}
          className="btn-ghost text-xs"
        >
          Cancel
        </button>
      </div>

      {/* Error Banner */}
      {state?.error && (
        <div
          className="mb-5 rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-inset ring-red-200"
          role="alert"
        >
          {state.error}
        </div>
      )}

      <form action={formAction} className="space-y-5">
        {/* Row 1: Source + Country */}
        <div className="grid gap-4 sm:grid-cols-2">
          {/* Source */}
          <div>
            <label htmlFor="sourceId" className="label">
              Source <span className="text-red-500">*</span>
            </label>
            <select
              id="sourceId"
              name="sourceId"
              required
              defaultValue={editMapping?.sourceId ?? ""}
              className="input mt-1.5"
            >
              <option value="" disabled>
                Select a source…
              </option>
              {sourceOptions.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name} ({s.sourceType})
                </option>
              ))}
            </select>
          </div>

          {/* Country */}
          <div>
            <label htmlFor="countryId" className="label">
              Country <span className="text-red-500">*</span>
            </label>
            <select
              id="countryId"
              name="countryId"
              required
              defaultValue={editMapping?.countryId ?? ""}
              className="input mt-1.5"
            >
              <option value="" disabled>
                Select a country…
              </option>
              {countryOptions.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name} ({c.code})
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Row 2: Category + Priority */}
        <div className="grid gap-4 sm:grid-cols-2">
          {/* Category */}
          <div>
            <label htmlFor="categoryId" className="label">
              Category <span className="text-red-500">*</span>
            </label>
            <select
              id="categoryId"
              name="categoryId"
              required
              defaultValue={editMapping?.categoryId ?? ""}
              className="input mt-1.5"
            >
              <option value="" disabled>
                Select a category…
              </option>
              {categoryOptions.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name} — {c.level}
                </option>
              ))}
            </select>
          </div>

          {/* Priority */}
          <div>
            <label htmlFor="priority" className="label">
              Priority
            </label>
            <input
              id="priority"
              name="priority"
              type="number"
              defaultValue={editMapping?.priority ?? 0}
              className="input mt-1.5"
              style={{ maxWidth: "6rem" }}
            />
            <p className="mt-1 text-2xs text-body-muted">
              Higher = preferred source for this country + category
            </p>
          </div>
        </div>

        {/* Row 3: Status */}
        <div>
          <label htmlFor="status" className="label">
            Status
          </label>
          <select
            id="status"
            name="status"
            defaultValue={editMapping?.status ?? "ACTIVE"}
            className="input mt-1.5"
            style={{ maxWidth: "10rem" }}
          >
            <option value="ACTIVE">Active</option>
            <option value="INACTIVE">Inactive</option>
          </select>
          <p className="mt-1 text-2xs text-body-muted">
            Only active mappings are used by the fetcher.
          </p>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-3 pt-1">
          <SubmitButton isEditing={isEditing} />
          <button
            type="button"
            onClick={onCancel}
            className="btn-secondary"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}
