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, Loader2Icon, MailIcon } 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 ResetPasswordPage() {
  const navigate = useNavigate();
  const { t } = useTranslation("auth");
  const [email, setEmail] = useState("");
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    try {
      const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/update-password`,
      });

      if (resetError) {
        throw resetError;
      }

      setIsSubmitted(true);
    } catch (err) {
      console.error("Password reset error:", err);
      setError(err instanceof Error ? err.message : t("resetPassword.error"));
      toast.add({
        title: t("resetPassword.errorTitle"),
        description: t("resetPassword.error"),
        type: "error",
        position: "top-center",
      });
    } finally {
      setIsPending(false);
    }
  };

  if (isSubmitted) {
    return (
      <div
        className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5"
        onClick={() => navigate("/login")}
      >
        <div
          className={twMerge(
            "w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
            "border border-border",
            "shadow-xl"
          )}
          onClick={(e) => e.stopPropagation()}
        >
          <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("resetPassword.emailSent")}</h1>
              <Text className="text-muted-foreground">
                {t("resetPassword.checkInbox", { email })}
              </Text>
            </div>
            <div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
              <div className="flex gap-3">
                <MailIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
                <Text className="text-sm text-blue-800 dark:text-blue-200 text-left">
                  {t("resetPassword.emailInstructions")}
                </Text>
              </div>
            </div>
            <Link to="/login" className="block">
              <Button className="mt-4">{t("resetPassword.backToLogin")}</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"
      onClick={() => navigate("/login")}
    >
      <div
        className={twMerge(
          "w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
          "border border-border",
          "shadow-xl"
        )}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="space-y-6">
          <div className="text-center">
            <h1 className="text-3xl font-bold text-foreground mb-2">{t("resetPassword.title")}</h1>
            <Text className="text-muted-foreground">{t("resetPassword.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="email">{t("resetPassword.emailLabel")}</Label>
              <Input
                id="email"
                name="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t("resetPassword.emailPlaceholder")}
                required
                disabled={isPending}
                className="transition-opacity disabled:opacity-50"
              />
            </div>

            <Button className="w-full" type="submit" disabled={isPending}>
              {isPending ? (
                <>
                  <Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
                  {t("resetPassword.sending")}
                </>
              ) : (
                t("resetPassword.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("resetPassword.backToLogin")}
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
