import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Apple, Eye, EyeOff, Globe, RotateCw, Send } from "lucide-react";

import { client, type CaptchaResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function Divider() {
  return (
    <div className="my-5 flex items-center gap-4 text-xs font-medium uppercase text-muted-foreground/60">
      <div className="h-px flex-1 bg-border" />
      <span>or</span>
      <div className="h-px flex-1 bg-border" />
    </div>
  );
}

export function SocialButtons() {
  return (
    <div className="mt-6 grid grid-cols-3 gap-3">
      <Button className="h-11 rounded-xl border-border bg-background text-foreground hover:bg-muted" type="button" variant="outline">
        <Apple className="size-5 fill-current" aria-hidden="true" />
        <span className="sr-only">Continue with Apple</span>
      </Button>
      <Button className="h-11 rounded-xl border-border bg-background text-foreground hover:bg-muted" type="button" variant="outline">
        <Globe className="size-5 text-destructive" aria-hidden="true" />
        <span className="sr-only">Continue with Google</span>
      </Button>
      <Button className="h-11 rounded-xl border-border bg-background text-primary hover:bg-muted" type="button" variant="outline">
        <Send className="size-5 fill-current" aria-hidden="true" />
        <span className="sr-only">Continue with Twitter</span>
      </Button>
    </div>
  );
}

export function PasswordInput({
  id,
  name,
  placeholder,
  autoComplete = "current-password",
}: {
  id: string;
  name: string;
  placeholder: string;
  autoComplete?: string;
}) {
  const [visible, setVisible] = useState(false);

  return (
    <div className="relative">
      <Input
        className="h-11 rounded-xl border-input bg-background pr-11 text-sm placeholder:text-muted-foreground/50 focus-visible:ring-ring/20"
        autoComplete={autoComplete}
        id={id}
        name={name}
        placeholder={placeholder}
        required
        type={visible ? "text" : "password"}
      />
      <Button
        aria-label={visible ? "Hide password" : "Show password"}
        className="absolute right-1.5 top-1/2 size-9 -translate-y-1/2 text-muted-foreground hover:bg-transparent"
        onClick={() => setVisible((current) => !current)}
        type="button"
        variant="ghost"
      >
        {visible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
      </Button>
    </div>
  );
}

export function CaptchaField({
  onPublicKey,
}: {
  onPublicKey?: (publicKey: string) => void;
}) {
  const [captcha, setCaptcha] = useState<CaptchaResponse | null>(null);
  const [loading, setLoading] = useState(false);

  const loadCaptcha = useCallback(async () => {
    setLoading(true);
    try {
      const response = await client.authCaptcha({
        w: 140,
        h: 44,
        dark: false,
        rsa: true,
      });
      setCaptcha(response.data);
      if (response.data.rsa?.public_key) {
        onPublicKey?.(response.data.rsa.public_key);
      }
    } finally {
      setLoading(false);
    }
  }, [onPublicKey]);

  useEffect(() => {
    const timer = window.setTimeout(() => void loadCaptcha(), 0);
    return () => window.clearTimeout(timer);
  }, [loadCaptcha]);

  const src = captcha?.base64?.startsWith("data:")
    ? captcha.base64
    : `data:image/png;base64,${captcha?.base64 ?? ""}`;

  return (
    <div className="space-y-2">
      <Label className="text-sm font-semibold text-foreground" htmlFor="captcha">
        Captcha
      </Label>
      <div className="flex gap-3">
        <Input
          autoComplete="off"
          className="h-11 rounded-xl border-input bg-background text-sm placeholder:text-muted-foreground/50 focus-visible:ring-ring/20"
          id="captcha"
          inputMode="text"
          name="captcha"
          placeholder="Enter captcha…"
          required
        />
        <button
          aria-label="Refresh captcha"
          className="grid h-11 w-30 shrink-0 place-items-center rounded-xl border border-border bg-muted/40 text-muted-foreground"
          disabled={loading}
          onClick={() => void loadCaptcha()}
          type="button"
        >
          {captcha ? (
            <img alt="Captcha" className="h-9 max-w-28 object-contain" height={36} src={src} width={112} />
          ) : (
            <RotateCw className="size-4" />
          )}
        </button>
      </div>
    </div>
  );
}

export function TextField({
  id,
  label,
  name,
  placeholder,
  type = "text",
}: {
  id: string;
  label: string;
  name: string;
  placeholder: string;
  type?: string;
}) {
  return (
    <div className="space-y-2">
      <Label className="text-sm font-semibold text-foreground" htmlFor={id}>
        {label}
      </Label>
      <Input
        autoComplete={type === "email" ? "email" : name === "username" ? "username" : "off"}
        className="h-11 rounded-xl border-input bg-background text-sm placeholder:text-muted-foreground/50 focus-visible:ring-ring/20"
        id={id}
        name={name}
        placeholder={placeholder}
        required
        spellCheck={type === "email" || name === "username" ? false : undefined}
        type={type}
      />
    </div>
  );
}

export function FormMessage({ children, tone }: { children: ReactNode; tone: "error" | "success" }) {
  return (
    <p
      aria-live="polite"
      className={
        tone === "error"
          ? "rounded-xl bg-destructive/10 px-3 py-2 text-sm text-destructive"
          : "rounded-xl bg-primary/10 px-3 py-2 text-sm text-primary"
      }
    >
      {children}
    </p>
  );
}
