"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "@turbostarter/i18n";
import { cn } from "@turbostarter/ui";

import { BusinessCard } from "./business-card";

import type { BusinessData } from "./wizard";

interface StepFindBusinessProps {
  onSelect: (business: BusinessData) => void;
}

export const StepFindBusiness = ({ onSelect }: StepFindBusinessProps) => {
  const { t } = useTranslation("marketing");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<BusinessData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [searched, setSearched] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);

  const search = useCallback(async (q: string) => {
    if (q.trim().length < 2) {
      setResults([]);
      setSearched(false);
      return;
    }

    setLoading(true);
    setError("");

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

      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as Record<string, string>;
        setError(data.error || t("wizard.findBusiness.error"));
        setResults([]);
      } else {
        const data = (await res.json()) as { businesses: BusinessData[] };
        setResults(data.businesses || []);
      }
    } catch {
      setError(t("wizard.findBusiness.error"));
      setResults([]);
    } finally {
      setLoading(false);
      setSearched(true);
    }
  }, [t]);

  const handleInputChange = (value: string) => {
    setQuery(value);

    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }

    const isUrl = /(?:google\.com\/maps|maps\.google\.com|goo\.gl\/maps|maps\.app\.goo\.gl)/i.test(value);

    if (isUrl && value.trim().length > 10) {
      search(value);
      return;
    }

    debounceRef.current = setTimeout(() => {
      if (value.trim().length >= 3) {
        search(value);
      }
    }, 500);
  };

  useEffect(() => {
    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, []);

  const isUrl = /(?:google\.com\/maps|maps\.google\.com|goo\.gl\/maps|maps\.app\.goo\.gl)/i.test(query);

  return (
    <div className="flex w-full max-w-lg flex-col items-center gap-6">
      <div className="text-center">
        <h2 className="text-foreground text-2xl font-semibold tracking-tight sm:text-3xl">
          {t("wizard.findBusiness.title")}
        </h2>
        <p className="text-muted-foreground mt-2 text-sm">
          {t("wizard.findBusiness.description")}
        </p>
      </div>

      <div className="relative w-full">
        <div className="relative">
          <svg
            className="text-muted-foreground pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
            />
          </svg>
          <input
            type="text"
            value={query}
            onChange={(e) => handleInputChange(e.target.value)}
            placeholder={t("wizard.findBusiness.placeholder")}
            className={cn(
              "border-input bg-background text-foreground placeholder:text-muted-foreground w-full rounded-xl border py-3 pl-10 pr-4 text-sm shadow-sm outline-none transition-colors",
              "focus:border-primary focus:ring-primary/20 focus:ring-2",
            )}
            autoFocus
          />
          {isUrl && (
            <span className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md bg-green-500/10 px-2 py-0.5 text-xs text-green-600">
              {t("wizard.findBusiness.urlDetected")}
            </span>
          )}
        </div>
      </div>

      {loading && (
        <div className="flex items-center gap-2">
          <div className="border-primary size-4 animate-spin rounded-full border-2 border-t-transparent" />
          <span className="text-muted-foreground text-sm">
            {t("wizard.findBusiness.searching")}
          </span>
        </div>
      )}

      {error && (
        <p className="text-sm text-red-500">{error}</p>
      )}

      {!loading && searched && results.length === 0 && !error && (
        <p className="text-muted-foreground text-center text-sm">
          {t("wizard.findBusiness.noResults")}
        </p>
      )}

      {results.length > 0 && (
        <div className="flex w-full flex-col gap-2">
          {results.map((business) => (
            <BusinessCard
              key={business.place_id || business.name}
              business={business}
              onClick={() => onSelect(business)}
            />
          ))}
        </div>
      )}
    </div>
  );
};
