"use client";

import { useState } from "react";
import Link from "next/link";

interface ParsedRate {
  duration: string;
  incall: string | null;
  outcall: string | null;
}

interface ParsedProfile {
  name: string | null;
  bio: string | null;
  photos: string[];
  services: string[];
  location: string | null;
  age: string | null;
  rates: ParsedRate[];
}

type Step = "enter-url" | "preview" | "success";

export default function ImportProfilePage() {
  const [step, setStep] = useState<Step>("enter-url");
  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [profile, setProfile] = useState<ParsedProfile | null>(null);

  // Checkboxes for what to include
  const [includeName, setIncludeName] = useState(true);
  const [includeBio, setIncludeBio] = useState(true);
  const [includeServices, setIncludeServices] = useState(true);
  const [includeLocation, setIncludeLocation] = useState(true);

  // Editable bio
  const [editedBio, setEditedBio] = useState("");

  async function handleFetch() {
    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/import/adultwork", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: url.trim() }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Failed to fetch profile.");
        return;
      }

      setProfile(data.profile);
      setEditedBio(data.profile.bio || "");
      setStep("preview");
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  async function handleImport() {
    if (!profile) return;
    setError(null);
    setSaving(true);

    try {
      const payload: Record<string, unknown> = {};
      if (includeName && profile.name) payload.name = profile.name;
      if (includeBio && editedBio.trim()) payload.bio = editedBio.trim();
      if (includeLocation && profile.location) payload.location = profile.location;
      if (includeServices && profile.services.length > 0) payload.services = profile.services;

      const res = await fetch("/api/import/adultwork", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Failed to save profile.");
        return;
      }

      setStep("success");
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-2">
        Import from AdultWork
      </h1>
      <p className="text-text-muted mb-8">
        Import your existing AdultWork profile to quickly set up your AdultWorld
        presence.
      </p>

      {/* Step indicator */}
      <div className="flex items-center gap-2 mb-8">
        {[
          { key: "enter-url", label: "1. Enter URL" },
          { key: "preview", label: "2. Preview & Select" },
          { key: "success", label: "3. Done" },
        ].map((s, i) => (
          <div key={s.key} className="flex items-center gap-2">
            {i > 0 && (
              <div
                className={`h-px w-8 ${
                  step === s.key || (s.key === "success" && step === "success")
                    ? "bg-primary"
                    : "bg-surface-light"
                }`}
              />
            )}
            <span
              className={`text-sm font-medium px-3 py-1 rounded-full ${
                step === s.key
                  ? "bg-primary text-white"
                  : step === "success" ||
                      (step === "preview" && s.key === "enter-url")
                    ? "bg-primary/20 text-primary"
                    : "bg-surface-light text-text-muted"
              }`}
            >
              {s.label}
            </span>
          </div>
        ))}
      </div>

      {/* Disclaimer */}
      <div className="bg-amber-900/20 border border-amber-700/40 rounded-lg p-4 mb-6">
        <p className="text-amber-300 text-sm">
          By importing, you confirm this is <strong>your own</strong> AdultWork
          profile and you have the right to use this content. We only read
          publicly visible information.
        </p>
      </div>

      {error && (
        <div className="bg-red-900/30 border border-red-700/40 text-red-400 rounded-lg p-4 mb-6 text-sm">
          {error}
        </div>
      )}

      {/* Step 1: Enter URL */}
      {step === "enter-url" && (
        <div className="bg-surface rounded-xl border border-surface-light p-6">
          <h2 className="text-lg font-semibold text-text mb-4">
            Enter your AdultWork profile URL
          </h2>
          <p className="text-text-muted text-sm mb-4">
            Paste the full URL of your public AdultWork profile page. For
            example:{" "}
            <span className="text-text font-mono text-xs">
              https://www.adultwork.com/ViewProfile.asp?UserID=12345
            </span>
          </p>

          <div className="flex gap-3">
            <input
              type="url"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="https://www.adultwork.com/..."
              className="flex-1 bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary"
              disabled={loading}
            />
            <button
              onClick={handleFetch}
              disabled={loading || !url.trim()}
              className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50 flex items-center gap-2 whitespace-nowrap"
            >
              {loading ? (
                <>
                  <svg
                    className="animate-spin w-4 h-4"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <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>
                  Fetching...
                </>
              ) : (
                "Fetch Profile"
              )}
            </button>
          </div>
        </div>
      )}

      {/* Step 2: Preview & Select */}
      {step === "preview" && profile && (
        <div className="space-y-6">
          {/* Name */}
          <div className="bg-surface rounded-xl border border-surface-light p-6">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-lg font-semibold text-text">Display Name</h3>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={includeName}
                  onChange={(e) => setIncludeName(e.target.checked)}
                  className="w-4 h-4 rounded border-surface-light text-primary focus:ring-primary bg-background"
                />
                <span className="text-sm text-text-muted">Include</span>
              </label>
            </div>
            {profile.name ? (
              <p
                className={`text-text ${!includeName ? "opacity-40 line-through" : ""}`}
              >
                {profile.name}
              </p>
            ) : (
              <p className="text-text-muted italic">No name found</p>
            )}
          </div>

          {/* Bio */}
          <div className="bg-surface rounded-xl border border-surface-light p-6">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-lg font-semibold text-text">Bio / Description</h3>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={includeBio}
                  onChange={(e) => setIncludeBio(e.target.checked)}
                  className="w-4 h-4 rounded border-surface-light text-primary focus:ring-primary bg-background"
                />
                <span className="text-sm text-text-muted">Include</span>
              </label>
            </div>
            {editedBio || profile.bio ? (
              <textarea
                value={editedBio}
                onChange={(e) => setEditedBio(e.target.value)}
                rows={6}
                disabled={!includeBio}
                className={`w-full bg-background border border-surface-light rounded-lg px-4 py-3 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-y ${!includeBio ? "opacity-40" : ""}`}
              />
            ) : (
              <p className="text-text-muted italic">No bio found</p>
            )}
          </div>

          {/* Photos */}
          {profile.photos.length > 0 && (
            <div className="bg-surface rounded-xl border border-surface-light p-6">
              <h3 className="text-lg font-semibold text-text mb-3">
                Photos Found ({profile.photos.length})
              </h3>
              <p className="text-text-muted text-sm mb-4">
                Photos are shown as a preview. Due to copyright and hosting
                restrictions, photos are not automatically imported. You can
                download and re-upload them from your{" "}
                <Link
                  href="/manage/photos/photos-profile"
                  className="text-primary hover:underline"
                >
                  photo manager
                </Link>
                .
              </p>
              <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
                {profile.photos.map((photo, i) => (
                  <div
                    key={i}
                    className="aspect-square bg-surface-light rounded-lg overflow-hidden border border-surface-light"
                  >
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={photo}
                      alt={`Photo ${i + 1}`}
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        (e.target as HTMLImageElement).style.display = "none";
                      }}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Services */}
          {profile.services.length > 0 && (
            <div className="bg-surface rounded-xl border border-surface-light p-6">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-lg font-semibold text-text">
                  Services ({profile.services.length})
                </h3>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={includeServices}
                    onChange={(e) => setIncludeServices(e.target.checked)}
                    className="w-4 h-4 rounded border-surface-light text-primary focus:ring-primary bg-background"
                  />
                  <span className="text-sm text-text-muted">Include</span>
                </label>
              </div>
              <div
                className={`flex flex-wrap gap-2 ${!includeServices ? "opacity-40" : ""}`}
              >
                {profile.services.map((service, i) => (
                  <span
                    key={i}
                    className="bg-primary/10 text-primary border border-primary/30 text-sm px-3 py-1 rounded-full"
                  >
                    {service}
                  </span>
                ))}
              </div>
              <p className="text-text-muted text-xs mt-3">
                Services will be matched to existing categories where possible.
                Unmatched services are skipped.
              </p>
            </div>
          )}

          {/* Location */}
          {profile.location && (
            <div className="bg-surface rounded-xl border border-surface-light p-6">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-lg font-semibold text-text">Location</h3>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={includeLocation}
                    onChange={(e) => setIncludeLocation(e.target.checked)}
                    className="w-4 h-4 rounded border-surface-light text-primary focus:ring-primary bg-background"
                  />
                  <span className="text-sm text-text-muted">Include</span>
                </label>
              </div>
              <p
                className={`text-text ${!includeLocation ? "opacity-40 line-through" : ""}`}
              >
                {profile.location}
              </p>
              <p className="text-text-muted text-xs mt-2">
                Location will be matched to the nearest city in our database.
              </p>
            </div>
          )}

          {/* Age */}
          {profile.age && (
            <div className="bg-surface rounded-xl border border-surface-light p-6">
              <h3 className="text-lg font-semibold text-text mb-2">Age</h3>
              <p className="text-text">{profile.age}</p>
              <p className="text-text-muted text-xs mt-1">
                Age is shown for reference only and is not imported.
              </p>
            </div>
          )}

          {/* Rates */}
          {profile.rates.length > 0 && (
            <div className="bg-surface rounded-xl border border-surface-light p-6">
              <h3 className="text-lg font-semibold text-text mb-3">
                Rates ({profile.rates.length})
              </h3>
              <p className="text-text-muted text-sm mb-3">
                Rates are shown for reference. Please set your rates manually in
                the{" "}
                <Link
                  href="/manage/rates"
                  className="text-primary hover:underline"
                >
                  rates manager
                </Link>{" "}
                to ensure accuracy.
              </p>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-surface-light">
                      <th className="text-left text-text-muted py-2 pr-4">
                        Duration
                      </th>
                      <th className="text-left text-text-muted py-2 pr-4">
                        Incall
                      </th>
                      <th className="text-left text-text-muted py-2">
                        Outcall
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {profile.rates.map((rate, i) => (
                      <tr
                        key={i}
                        className="border-b border-surface-light/50 last:border-0"
                      >
                        <td className="py-2 pr-4 text-text">
                          {rate.duration}
                        </td>
                        <td className="py-2 pr-4 text-text">
                          {rate.incall || "-"}
                        </td>
                        <td className="py-2 text-text">
                          {rate.outcall || "-"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* No data found notice */}
          {!profile.name &&
            !profile.bio &&
            profile.photos.length === 0 &&
            profile.services.length === 0 &&
            !profile.location &&
            profile.rates.length === 0 && (
              <div className="bg-surface rounded-xl border border-surface-light p-6 text-center">
                <p className="text-text-muted">
                  No profile data could be extracted from the page. The profile
                  structure may not be supported, or the page may require login
                  to view.
                </p>
                <button
                  onClick={() => setStep("enter-url")}
                  className="mt-4 text-primary hover:underline text-sm"
                >
                  Try a different URL
                </button>
              </div>
            )}

          {/* Action buttons */}
          <div className="flex items-center gap-4">
            <button
              onClick={() => setStep("enter-url")}
              className="text-text-muted hover:text-text text-sm transition-colors"
            >
              Back
            </button>
            <button
              onClick={handleImport}
              disabled={saving}
              className="bg-primary hover:bg-primary-dark text-white px-8 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50 flex items-center gap-2"
            >
              {saving ? (
                <>
                  <svg
                    className="animate-spin w-4 h-4"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <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>
                  Importing...
                </>
              ) : (
                "Import Selected"
              )}
            </button>
          </div>
        </div>
      )}

      {/* Step 3: Success */}
      {step === "success" && (
        <div className="bg-surface rounded-xl border border-surface-light p-8 text-center">
          <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg
              className="w-8 h-8 text-green-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M5 13l4 4L19 7"
              />
            </svg>
          </div>
          <h2 className="text-2xl font-bold text-text mb-2">
            Profile imported successfully!
          </h2>
          <p className="text-text-muted mb-6">
            Your selected AdultWork profile data has been imported. You can
            review and fine-tune your profile at any time.
          </p>
          <div className="flex items-center justify-center gap-4">
            <Link
              href="/manage/profile/personal-information"
              className="bg-surface-light hover:bg-surface-lighter text-text px-6 py-2.5 rounded-lg font-medium transition-colors"
            >
              Edit Profile
            </Link>
            <Link
              href="/dashboard/provider"
              className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors"
            >
              Go to Dashboard
            </Link>
          </div>
        </div>
      )}
    </div>
  );
}
