"use client";

import { useState, useEffect, useCallback } from "react";

interface SubdomainPickerProps {
  value: string;
  onChange: (value: string) => void;
}

export default function SubdomainPicker({ value, onChange }: SubdomainPickerProps) {
  const [checking, setChecking] = useState(false);
  const [available, setAvailable] = useState<boolean | null>(null);

  const slug = value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");

  const checkAvailability = useCallback(async (s: string) => {
    if (s.length < 3) {
      setAvailable(null);
      return;
    }
    setChecking(true);
    try {
      const res = await fetch(`/api/check-subdomain?slug=${encodeURIComponent(s)}`);
      const data = await res.json();
      setAvailable(data.available);
    } catch {
      setAvailable(null);
    } finally {
      setChecking(false);
    }
  }, []);

  useEffect(() => {
    const timer = setTimeout(() => {
      checkAvailability(slug);
    }, 500);
    return () => clearTimeout(timer);
  }, [slug, checkAvailability]);

  return (
    <div className="space-y-4">
      <div>
        <label htmlFor="subdomain" className="block text-sm font-medium text-stone-700">
          Изберете поддомен
        </label>
        <div className="mt-1 flex items-center rounded-lg border border-stone-200 bg-white">
          <input
            id="subdomain"
            type="text"
            value={value}
            onChange={(e) => onChange(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-"))}
            placeholder="нпр. maria-novakovska"
            className="flex-1 rounded-l-lg border-0 px-3 py-2 text-stone-900 placeholder:text-stone-400 focus:outline-none focus:ring-1 focus:ring-primary"
            maxLength={63}
          />
          <span className="rounded-r-lg bg-stone-50 px-3 py-2 text-sm text-stone-500 border-l border-stone-200">
            .{process.env.NEXT_PUBLIC_APP_DOMAIN || "testbed.mk"}
          </span>
        </div>
      </div>

      <div className="text-sm">
        {checking && <p className="text-stone-500">Проверка на достапност...</p>}
        {!checking && available === true && (
          <p className="text-green-600">&#10003; {slug}.testbed.mk е достапен!</p>
        )}
        {!checking && available === false && (
          <p className="text-red-600">&#10007; Овој поддомен е веќе зафатен.</p>
        )}
        {!checking && available === null && slug.length > 0 && slug.length < 3 && (
          <p className="text-stone-400">Потребни се најмалку 3 карактери.</p>
        )}
      </div>
    </div>
  );
}