import { toast } from "@xtablo/shared";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { Text } from "@xtablo/ui/components/typography";
import { AlertCircle, CheckCircle2, EyeIcon, EyeOffIcon, Loader2Icon } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { twMerge } from "tailwind-merge";
import { supabase } from "../lib/supabase";

export function UpdatePasswordPage() {
  const navigate = useNavigate();
  const { t } = useTranslation("auth");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSuccess, setIsSuccess] = useState(false);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsPending(true);
    setError(null);

    // Validation
    if (password.length < 8) {
      setError(t("signup.errors.passwordLength"));
      setIsPending(false);
      return;
    }

    if (password !== confirmPassword) {
      setError(t("signup.errors.passwordMatch"));
      setIsPending(false);
      return;
    }

    try {
      const { error: updateError } = await supabase.auth.updateUser({
        password: password,
      });

      if (updateError) {
        throw updateError;
      }

      setIsSuccess(true);
      toast.add({
        title: t("updatePassword.successTitle"),
        description: t("updatePassword.successDescription"),
        type: "success",
        position: "top-center",
      });

      // Redirect to login after 2 seconds
      setTimeout(() => {
        navigate("/login");
      }, 2000);
    } catch (err) {
      console.error("Password update error:", err);
      setError(err instanceof Error ? err.message : t("updatePassword.error"));
      toast.add({
        title: t("updatePassword.errorTitle"),
        description: t("updatePassword.error"),
        type: "error",
        position: "top-center",
      });
    } finally {
      setIsPending(false);
    }
  };

  if (isSuccess) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5">
        <div
          className={twMerge(
            "w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
            "border border-border",
            "shadow-xl"
          )}
        >
          <div className="text-center space-y-6">
            <div className="flex justify-center">
              <div className="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
                <CheckCircle2 className="w-12 h-12 text-green-600 dark:text-green-400" />
              </div>
            </div>
            <div className="space-y-2">
              <h1 className="text-3xl font-bold text-foreground">
                {t("updatePassword.successTitle")}
              </h1>
              <Text className="text-muted-foreground">
                {t("updatePassword.successDescription")}
              </Text>
            </div>
            <Link to="/login" className="block">
              <Button className="mt-4">{t("updatePassword.goToLogin")}</Button>
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5">
      <div
        className={twMerge(
          "w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
          "border border-border",
          "shadow-xl"
        )}
      >
        <div className="space-y-6">
          <div className="text-center">
            <h1 className="text-3xl font-bold text-foreground mb-2">{t("updatePassword.title")}</h1>
            <Text className="text-muted-foreground">{t("updatePassword.description")}</Text>
          </div>

          {error && (
            <div className="bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
              <div className="flex gap-3">
                <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0" />
                <Text className="text-sm text-red-800 dark:text-red-200">{error}</Text>
              </div>
            </div>
          )}

          <form className="space-y-4" onSubmit={onSubmit}>
            <div className="space-y-2">
              <Label htmlFor="password">{t("updatePassword.passwordLabel")}</Label>
              <div className="relative">
                <Input
                  id="password"
                  name="password"
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder={t("updatePassword.passwordPlaceholder")}
                  required
                  disabled={isPending}
                  className="pr-10 transition-opacity disabled:opacity-50"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  disabled={isPending}
                >
                  {showPassword ? (
                    <EyeOffIcon className="w-4 h-4" />
                  ) : (
                    <EyeIcon className="w-4 h-4" />
                  )}
                </button>
              </div>
              <p className="text-xs text-muted-foreground">
                {t("updatePassword.passwordRequirements")}
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword">{t("updatePassword.confirmPasswordLabel")}</Label>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  name="confirmPassword"
                  type={showConfirmPassword ? "text" : "password"}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder={t("updatePassword.confirmPasswordPlaceholder")}
                  required
                  disabled={isPending}
                  className="pr-10 transition-opacity disabled:opacity-50"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  disabled={isPending}
                >
                  {showConfirmPassword ? (
                    <EyeOffIcon className="w-4 h-4" />
                  ) : (
                    <EyeIcon className="w-4 h-4" />
                  )}
                </button>
              </div>
            </div>

            <Button className="w-full" type="submit" disabled={isPending}>
              {isPending ? (
                <>
                  <Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
                  {t("updatePassword.updating")}
                </>
              ) : (
                t("updatePassword.submit")
              )}
            </Button>
          </form>

          <p className="text-center text-sm text-muted-foreground">
            <Link
              to="/login"
              className="text-foreground hover:text-foreground/80 font-medium transition-colors"
            >
              {t("updatePassword.backToLogin")}
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
