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

import { useFormState, useFormStatus } from "react-dom";
import { createCountry, updateCountry } from "./actions";

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

interface EditCountryInput {
  id: string;
  name: string;
  code: string;
  region: string | null;
  defaultLanguage: string;
  isGlobal: boolean;
  status: string;
  displayOrder: number;
}

interface CountryFormProps {
  /** If provided, the form is in edit mode and pre-fills with this data. */
  editCountry?: EditCountryInput | null;
  /** Called when the user cancels the form. */
  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 Country"
      )}
    </button>
  );
}

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

export default function CountryForm({ editCountry, onCancel }: CountryFormProps) {
  const isEditing = !!editCountry;

  // Bind the appropriate server action.
  // For edit mode, bind the country ID as the first argument.
  const action = editCountry
    ? updateCountry.bind(null, editCountry.id)
    : createCountry;

  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 Country" : "Add Country"}
        </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: Name + Code */}
        <div className="grid gap-4 sm:grid-cols-2">
          {/* Name */}
          <div>
            <label htmlFor="name" className="label">
              Name <span className="text-red-500">*</span>
            </label>
            <input
              id="name"
              name="name"
              type="text"
              required
              defaultValue={editCountry?.name ?? ""}
              placeholder="e.g., United States"
              className="input mt-1.5"
            />
          </div>

          {/* Code */}
          <div>
            <label htmlFor="code" className="label">
              ISO Code <span className="text-red-500">*</span>
            </label>
            <input
              id="code"
              name="code"
              type="text"
              required
              maxLength={2}
              defaultValue={editCountry?.code ?? ""}
              placeholder="e.g., US"
              className="input mt-1.5 uppercase"
              style={{ maxWidth: "6rem" }}
            />
            <p className="mt-1 text-2xs text-body-muted">
              2-letter ISO 3166-1 alpha-2 code
            </p>
          </div>
        </div>

        {/* Row 2: Region + Language */}
        <div className="grid gap-4 sm:grid-cols-2">
          {/* Region */}
          <div>
            <label htmlFor="region" className="label">
              Region
            </label>
            <input
              id="region"
              name="region"
              type="text"
              defaultValue={editCountry?.region ?? ""}
              placeholder="e.g., North America"
              className="input mt-1.5"
            />
          </div>

          {/* Default Language */}
          <div>
            <label htmlFor="defaultLanguage" className="label">
              Default Language
            </label>
            <input
              id="defaultLanguage"
              name="defaultLanguage"
              type="text"
              defaultValue={editCountry?.defaultLanguage ?? "en"}
              placeholder="en"
              className="input mt-1.5"
              style={{ maxWidth: "5rem" }}
            />
            <p className="mt-1 text-2xs text-body-muted">
              ISO 639-1 language code
            </p>
          </div>
        </div>

        {/* Row 3: Display Order + Status + Global */}
        <div className="grid gap-4 sm:grid-cols-3">
          {/* Display Order */}
          <div>
            <label htmlFor="displayOrder" className="label">
              Display Order
            </label>
            <input
              id="displayOrder"
              name="displayOrder"
              type="number"
              min={0}
              defaultValue={editCountry?.displayOrder ?? 0}
              className="input mt-1.5"
              style={{ maxWidth: "6rem" }}
            />
          </div>

          {/* Status */}
          <div>
            <label htmlFor="status" className="label">
              Status
            </label>
            <select
              id="status"
              name="status"
              defaultValue={editCountry?.status ?? "ACTIVE"}
              className="input mt-1.5"
            >
              <option value="ACTIVE">Active</option>
              <option value="INACTIVE">Inactive</option>
            </select>
          </div>

          {/* Global Toggle */}
          <div className="flex items-end pb-0.5">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                id="isGlobal"
                name="isGlobal"
                type="checkbox"
                defaultChecked={editCountry?.isGlobal ?? false}
                className="h-4 w-4 rounded border-border text-brand-600 focus:ring-brand-500"
              />
              <span className="select-none">
                <span className="text-sm font-medium text-heading">
                  Global Country
                </span>
                <span className="ml-1 text-xs text-body-muted">
                  (World / all regions)
                </span>
              </span>
            </label>
          </div>
        </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>
  );
}
