import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { AtSign, Loader2, Save } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

const USERNAME_PATTERN = /^[A-Za-z0-9._-]{3,32}$/;

export default function UsernameCard({ userId }: { userId: string }) {
  const [username, setUsername] = useState("");
  const [original, setOriginal] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!userId) return;
    (async () => {
      setLoading(true);
      const { data } = await supabase
        .from("profiles")
        .select("username")
        .eq("user_id", userId)
        .maybeSingle();
      const current = (data as any)?.username || "";
      setUsername(current);
      setOriginal(current);
      setLoading(false);
    })();
  }, [userId]);

  const handleSave = async () => {
    const trimmed = username.trim();
    if (trimmed && !USERNAME_PATTERN.test(trimmed)) {
      toast.error("Username must be 3–32 characters: letters, numbers, dot, underscore or hyphen");
      return;
    }
    setSaving(true);
    const { error } = await supabase
      .from("profiles")
      .update({ username: trimmed || null } as any)
      .eq("user_id", userId);
    setSaving(false);
    if (error) {
      if (error.code === "23505") toast.error("That username is already taken");
      else toast.error(error.message || "Failed to save username");
      return;
    }
    setOriginal(trimmed);
    toast.success(trimmed ? "Username saved" : "Username cleared");
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <AtSign className="h-5 w-5 text-primary" /> Username
        </CardTitle>
        <CardDescription>
          Pick a username so you can sign in without typing your email. You can still log in with your email anytime.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="username">Username</Label>
          <Input
            id="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="e.g. jane.doe"
            disabled={loading}
            maxLength={32}
            autoComplete="username"
          />
          <p className="text-xs text-muted-foreground">
            3–32 characters. Letters, numbers, dot (.), underscore (_) or hyphen (-). Leave blank to remove.
          </p>
        </div>
        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving || loading || username === original} className="gap-2">
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            {saving ? "Saving…" : "Save Username"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
