"use client";
import { useState, FormEvent, useEffect } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Loader2, Globe } from "lucide-react";

export default function AddSubdomainPage() {
  const router = useRouter();
  const [subdomain, setSubdomain] = useState<string>("");
  const [error, setError] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const trimmedSubdomain = subdomain.trim();

    if (!trimmedSubdomain) {
      setError("Please enter a subdomain name.");
      return;
    }

    setError("");
    setIsSubmitting(true);

    const redirectToSubdomain = (target: string) => {
      const [hostnameOnly, port] = window.location.host.split(":");
      const portSegment = port ? `:${port}` : "";
      
      if (hostnameOnly === "localhost" || hostnameOnly.startsWith("localhost")) {
        router.push(`/${encodeURIComponent(target)}/login`);
        return;
      }

      // For production, construct the subdomain URL
      let targetHostname: string;
      
      if (hostnameOnly === "core.yousystems.com") {
        targetHostname = `${target}.core.yousystems.com`;
      } else if (hostnameOnly.endsWith(".core.yousystems.com")) {
        const baseDomain = hostnameOnly.replace(/^[^.]+\./, "");
        targetHostname = `${target}.${baseDomain}`;
      } else {
        targetHostname = `${target}.${hostnameOnly}`;
      }

      window.location.assign(
        `${window.location.protocol}//${targetHostname}${portSegment}/login`
      );
    };

    try {
      const response = await fetch("/api/add-subdomain", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ subdomain: trimmedSubdomain }),
      });

      if (response.ok) {
        redirectToSubdomain(trimmedSubdomain);
        return;
      }

      const errorBody = await response.json().catch(() => null);
      setError(
        errorBody?.error ??
          "Something went wrong while adding the subdomain. Please try again."
      );
    } catch {
      setError("Unable to reach the server. Please try again in a moment.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="grid min-h-screen bg-gradient-to-br from-white via-[#f4f8f5] to-white lg:grid-cols-2">
      <div className="flex flex-col gap-6 px-6 py-10 md:px-12 lg:px-16">
        <div 
          className={`flex items-center justify-between select-none transition-all duration-700 ${
            mounted ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-4"
          }`}
        >
          <a href="/" className="flex items-center gap-2 transition-transform hover:scale-105">
            <Image
              src="/assets/oxy-logo.png"
              alt="Oxyfinz Logo"
              width={200}
              height={40}
              priority
            />
          </a>
        </div>

        <div className="flex flex-1 items-center justify-center">
          <div 
            className={`w-full max-w-sm rounded-lg border border-white/60 bg-white/90 p-8 shadow-xl backdrop-blur transition-all duration-700 delay-200 ${
              mounted ? "opacity-100 translate-y-0 scale-100" : "opacity-0 translate-y-8 scale-95"
            }`}
          >
            <div 
              className={`space-y-2 text-center transition-all duration-700 delay-300 ${
                mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
              }`}
            >
              <h1 className="text-2xl font-semibold text-slate-800">Add Subdomain</h1>
              <p className="text-sm text-slate-500">
                Create or access a subdomain workspace. Each subdomain gets its own secure entry point.
              </p>
            </div>
            <div 
              className={`mt-8 space-y-3 transition-all duration-700 delay-400 ${
                mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
              }`}
            >
              <form
                onSubmit={handleSubmit}
                className="flex flex-col gap-6"
                noValidate
              >
                <FieldGroup>
                  {error && (
                    <p
                      role="alert"
                      className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600 text-center animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
                    >
                      {error}
                    </p>
                  )}

                  <Field>
                    <FieldLabel
                      htmlFor="subdomain"
                      className={`text-xs font-semibold uppercase tracking-wide text-slate-500 transition-all duration-500 ${
                        mounted ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
                      }`}
                    >
                      Subdomain Name
                    </FieldLabel>
                    <div 
                      className={`relative transition-all duration-500 delay-100 ${
                        mounted ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
                      }`}
                    >
                      <Globe className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 transition-colors duration-200" />
                      <Input
                        id="subdomain"
                        type="text"
                        placeholder="e.g. beta-launch"
                        required
                        disabled={isSubmitting}
                        value={subdomain}
                        onChange={(event) => setSubdomain(event.target.value)}
                        className="pl-10 transition-all duration-200 focus:scale-[1.02]"
                      />
                    </div>
                    <p 
                      className={`mt-1 text-xs text-slate-400 transition-all duration-500 delay-200 ${
                        mounted ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
                      }`}
                    >
                      Use hyphenated, lowercase words. Existing names will redirect to the workspace.
                    </p>
                  </Field>

                  <Field>
                    <Button
                      type="submit"
                      disabled={isSubmitting}
                      className={`w-full rounded-lg bg-[#428B4D] px-4 py-3 text-sm font-semibold uppercase tracking-[0.3em] text-white transition-all duration-300 hover:bg-[#357a3f] hover:scale-[1.02] hover:shadow-lg disabled:opacity-70 disabled:hover:scale-100 ${
                        mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
                      }`}
                    >
                      {isSubmitting ? (
                        <span className="flex items-center justify-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          Processing...
                        </span>
                      ) : (
                        "Create or Access"
                      )}
                    </Button>
                  </Field>
                </FieldGroup>
              </form>
            </div>
            <p 
              className={`mt-6 text-center text-xs text-slate-500 transition-all duration-700 delay-500 ${
                mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
              }`}
            >
              Need assistance?{" "}
              <a
                href="mailto:support@oxyfinz.com"
                className="font-semibold text-[#428B4D] hover:underline transition-colors duration-200"
              >
                support@oxyfinz.com
              </a>
            </p>
          </div>
        </div>
      </div>

      <div 
        className={`relative hidden lg:block transition-all duration-1000 delay-300 ${
          mounted ? "opacity-100 scale-100" : "opacity-0 scale-105"
        }`}
      >
        <Image
          src="/assets/Signin_1.png"
          alt="Subdomain background"
          fill
          sizes="50vw"
          priority
          className="object-cover object-center"
        />
      </div>
    </div>
  );
}
