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

import { useState } from "react";
import { useFormState, useFormStatus } from "react-dom";
import { createSource, updateSource } from "./actions";

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

interface EditSourceInput {
  id: string;
  name: string;
  websiteUrl: string;
  sourceType: string;
  feedUrl: string | null;
  apiUrl: string | null;
  language: string;
  trustScore: number; // 1-10 display scale
  reliabilityScore: number;
  duplicateRate: number;
  clickbaitRate: number;
  isOfficial: boolean;
  status: string;
  fetchFrequencyMinutes: number;
  usageNotes: string | null;
}

interface SourceFormProps {
  /** If provided, the form is in edit mode and pre-fills with this data. */
  editSource?: EditSourceInput | 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 Source"
      )}
    </button>
  );
}

// ============================================================================
// Source Type Options
// ============================================================================

const SOURCE_TYPE_OPTIONS = [
  { value: "RSS", label: "RSS / Atom Feed" },
  { value: "API", label: "REST API" },
  { value: "MANUAL", label: "Manual Entry" },
  { value: "SCRAPE", label: "Web Scraping" },
] as const;

const STATUS_OPTIONS = [
  { value: "ACTIVE", label: "Active" },
  { value: "INACTIVE", label: "Inactive" },
  { value: "ERROR", label: "Error" },
  { value: "RATE_LIMITED", label: "Rate Limited" },
] as const;

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

export default function SourceForm({ editSource, onCancel }: SourceFormProps) {
  const isEditing = !!editSource;

  // Track source type for conditional field visibility
  const [sourceType, setSourceType] = useState<string>(
    editSource?.sourceType ?? "RSS",
  );

  // Bind the appropriate server action.
  const action = editSource
    ? updateSource.bind(null, editSource.id)
    : createSource;

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

  const showFeedUrl = sourceType === "RSS";
  const showApiUrl = sourceType === "API";
  const showScrapeWarning = sourceType === "SCRAPE";

  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" : "Add Source"}
        </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-6">
        {/* ── Section: Basic Info ── */}
        <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
              maxLength={200}
              defaultValue={editSource?.name ?? ""}
              placeholder="e.g., BBC News"
              className="input mt-1.5"
            />
          </div>

          {/* Website URL */}
          <div>
            <label htmlFor="websiteUrl" className="label">
              Website URL <span className="text-red-500">*</span>
            </label>
            <input
              id="websiteUrl"
              name="websiteUrl"
              type="url"
              required
              defaultValue={editSource?.websiteUrl ?? ""}
              placeholder="https://www.bbc.com/news"
              className="input mt-1.5"
            />
          </div>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          {/* Source Type */}
          <div>
            <label htmlFor="sourceType" className="label">
              Source Type <span className="text-red-500">*</span>
            </label>
            <select
              id="sourceType"
              name="sourceType"
              value={sourceType}
              onChange={(e) => setSourceType(e.target.value)}
              className="input mt-1.5"
            >
              {SOURCE_TYPE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>

          {/* Language */}
          <div>
            <label htmlFor="language" className="label">
              Language
            </label>
            <input
              id="language"
              name="language"
              type="text"
              defaultValue={editSource?.language ?? "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>

        {/* ── Section: Endpoint URLs (conditional) ── */}
        {(showFeedUrl || showApiUrl) && (
          <div className="border-t border-border pt-5">
            <h3 className="text-sm font-semibold text-heading mb-3">
              Endpoint Configuration
            </h3>

            {/* Feed URL — RSS */}
            {showFeedUrl && (
              <div>
                <label htmlFor="feedUrl" className="label">
                  Feed URL{" "}
                  <span className="text-red-500">*</span>
                </label>
                <input
                  id="feedUrl"
                  name="feedUrl"
                  type="url"
                  defaultValue={editSource?.feedUrl ?? ""}
                  placeholder="https://feeds.bbci.co.uk/news/rss.xml"
                  className="input mt-1.5"
                />
                <p className="mt-1 text-2xs text-body-muted">
                  Required for active RSS sources. Must be a publicly accessible RSS/Atom feed.
                </p>
              </div>
            )}

            {/* API URL — API */}
            {showApiUrl && (
              <div>
                <label htmlFor="apiUrl" className="label">
                  API URL{" "}
                  <span className="text-red-500">*</span>
                </label>
                <input
                  id="apiUrl"
                  name="apiUrl"
                  type="url"
                  defaultValue={editSource?.apiUrl ?? ""}
                  placeholder="https://newsapi.org/v2/top-headlines"
                  className="input mt-1.5"
                />
                <p className="mt-1 text-2xs text-body-muted">
                  Required for active API sources. Must be a publicly accessible REST endpoint.
                </p>
              </div>
            )}
          </div>
        )}

        {/* ── Section: Scores & Ratings ── */}
        <div className="border-t border-border pt-5">
          <h3 className="text-sm font-semibold text-heading mb-3">
            Scores &amp; Ratings
          </h3>

          <div className="grid gap-4 sm:grid-cols-2">
            {/* Trust Score */}
            <div>
              <label htmlFor="trustScore" className="label">
                Trust Score <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center gap-2 mt-1.5">
                <input
                  id="trustScore"
                  name="trustScore"
                  type="range"
                  min={1}
                  max={10}
                  defaultValue={editSource?.trustScore ?? 5}
                  className="flex-1 accent-brand-600"
                />
                <output
                  className="inline-flex h-7 w-7 items-center justify-center rounded bg-surface-tertiary text-xs font-mono font-semibold text-heading"
                  htmlFor="trustScore"
                >
                  {editSource?.trustScore ?? 5}
                </output>
              </div>
              <div className="flex justify-between mt-0.5">
                <span className="text-2xs text-body-muted">1 — Low trust</span>
                <span className="text-2xs text-body-muted">10 — High trust</span>
              </div>
            </div>

            {/* Reliability Score */}
            <div>
              <label htmlFor="reliabilityScore" className="label">
                Reliability Score
              </label>
              <input
                id="reliabilityScore"
                name="reliabilityScore"
                type="number"
                min={0}
                max={100}
                defaultValue={editSource?.reliabilityScore ?? 50}
                className="input mt-1.5"
                style={{ maxWidth: "5rem" }}
              />
              <p className="mt-1 text-2xs text-body-muted">
                Historical reliability 0–100
              </p>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2 mt-4">
            {/* Duplicate Rate */}
            <div>
              <label htmlFor="duplicateRate" className="label">
                Duplicate Rate (%)
              </label>
              <input
                id="duplicateRate"
                name="duplicateRate"
                type="number"
                min={0}
                max={100}
                step={0.1}
                defaultValue={editSource?.duplicateRate ?? 0}
                className="input mt-1.5"
                style={{ maxWidth: "5rem" }}
              />
            </div>

            {/* Clickbait Rate */}
            <div>
              <label htmlFor="clickbaitRate" className="label">
                Clickbait Rate (%)
              </label>
              <input
                id="clickbaitRate"
                name="clickbaitRate"
                type="number"
                min={0}
                max={100}
                step={0.1}
                defaultValue={editSource?.clickbaitRate ?? 0}
                className="input mt-1.5"
                style={{ maxWidth: "5rem" }}
              />
            </div>
          </div>
        </div>

        {/* ── Section: Classification ── */}
        <div className="border-t border-border pt-5">
          <h3 className="text-sm font-semibold text-heading mb-3">
            Classification
          </h3>

          <div className="grid gap-4 sm:grid-cols-2">
            {/* Status */}
            <div>
              <label htmlFor="status" className="label">
                Status
              </label>
              <select
                id="status"
                name="status"
                defaultValue={editSource?.status ?? "ACTIVE"}
                className="input mt-1.5"
              >
                {STATUS_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            {/* Official Source */}
            <div className="flex items-end pb-0.5">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  id="isOfficial"
                  name="isOfficial"
                  type="checkbox"
                  defaultChecked={editSource?.isOfficial ?? 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">
                    Official Source
                  </span>
                  <span className="ml-1 text-xs text-body-muted">
                    (Government / institutional)
                  </span>
                </span>
              </label>
            </div>
          </div>
        </div>

        {/* ── Section: Settings ── */}
        <div className="border-t border-border pt-5">
          <h3 className="text-sm font-semibold text-heading mb-3">
            Settings
          </h3>

          <div className="grid gap-4 sm:grid-cols-2">
            {/* Fetch Frequency */}
            <div>
              <label htmlFor="fetchFrequencyMinutes" className="label">
                Fetch Frequency (minutes)
              </label>
              <input
                id="fetchFrequencyMinutes"
                name="fetchFrequencyMinutes"
                type="number"
                min={1}
                defaultValue={editSource?.fetchFrequencyMinutes ?? 15}
                className="input mt-1.5"
                style={{ maxWidth: "6rem" }}
              />
            </div>

            {/* Usage Notes */}
            <div>
              <label htmlFor="usageNotes" className="label">
                Usage Notes
              </label>
              <textarea
                id="usageNotes"
                name="usageNotes"
                rows={3}
                defaultValue={editSource?.usageNotes ?? ""}
                placeholder="e.g., Rate limit: 100 req/hr. Requires API key in headers."
                className="input mt-1.5"
              />
            </div>
          </div>
        </div>

        {/* ── SCRAPE Warning ── */}
        {showScrapeWarning && (
          <div className="rounded-md bg-amber-50 p-3 text-sm text-amber-800 ring-1 ring-inset ring-amber-200">
            <span className="font-semibold">⚠️ Legal Notice:</span> Web scraping should
            only be used for sources that explicitly allow it in their terms of service
            or robots.txt. Ensure you have the legal right to scrape content from this
            website before activating this source.
          </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>
  );
}
