"use client";

import type React from "react";
import { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Phone, ArrowLeft, RefreshCw, Mail, Lock, Home } from "lucide-react";
import { toast } from "sonner";
import { useNavigate } from "react-router-dom";
import { isValidEthiopianPhone } from "@/record-management/common/editor/Utils";
import { requestForgotPassword } from "@/shared/services/authService";
import { useTranslation } from "react-i18next";

export const ForgotPassword = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [identifier, setIdentifier] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    let processedIdentifier = identifier;

    if (!isValidEthiopianPhone(processedIdentifier)) {
      setError(t("forgotpassword.invalidphone"));
      return;
    }

    if (processedIdentifier.startsWith("0")) {
      processedIdentifier = "+251" + processedIdentifier.slice(1);
    }

    setLoading(true);

    try {
      await requestForgotPassword(processedIdentifier);
      toast.success(t("forgotpassword.success"), {
        description: t("forgotpassword.successdesc"),
      });
      setTimeout(() => navigate("/"), 3000);
    } catch (error: any) {
      const message = error?.message || t("forgotpassword.fail");
      setError(message);
      toast.error(t("forgotpassword.fail"), { description: message });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 via-white to-primary-50 relative overflow-hidden">
      <div className="absolute top-0 right-0 w-96 h-96 bg-primary-100/30 rounded-full blur-3xl" />
      <div className="absolute bottom-0 left-0 w-96 h-96 bg-primary-100/30 rounded-full blur-3xl" />

      <button
        onClick={() => navigate("/")}
        className="absolute top-6 left-6 z-10 flex items-center gap-2 px-4 py-2 bg-white/80 backdrop-blur-sm hover:bg-white rounded-full shadow-md hover:shadow-lg transition-all duration-300 group"
      >
        <Home className="w-4 h-4 text-primary group-hover:scale-110 transition-transform" />
        <span className="text-sm font-medium text-gray-700">
          {t("forgotpassword.home")}
        </span>
      </button>

      <div className="relative min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-md">
          <div className="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden">
            <div className="bg-gradient-to-r from-primary to-primary-500 p-8 text-center relative">
              <div className="absolute inset-0 bg-white/5" />
              <div className="relative">
                <div className="w-16 h-16 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center mx-auto mb-4">
                  <Lock className="w-8 h-8 text-white" />
                </div>
                <h1 className="text-2xl font-bold text-white mb-2">
                  {t("forgotpassword.title")}
                </h1>
                <p className="text-primary-50 text-sm">
                  {t("forgotpassword.subtitle")}
                </p>
              </div>
            </div>

            <div className="p-8">
              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Phone className="w-4 h-4 text-primary" />
                    {t("forgotpassword.phone")}
                  </label>
                  <div className="relative">
                    <Input
                      type="tel"
                      placeholder={t("forgotpassword.phoneplaceholder")}
                      className="h-12 rounded-lg border-gray-200 px-4 text-sm focus:border-primary focus:ring-primary transition-all"
                      value={identifier}
                      onChange={(e) => {
                        setIdentifier(e.target.value);
                        setError("");
                      }}
                      required
                    />
                  </div>
                  {error && (
                    <div className="flex items-start gap-2 p-3 bg-red-50 border border-red-100 rounded-lg">
                      <div className="w-1 h-1 bg-red-500 rounded-full mt-1.5" />
                      <p className="text-sm text-red-600 flex-1">{error}</p>
                    </div>
                  )}
                </div>

                <div className="flex items-start gap-3 p-4 bg-primary-50 border border-primary-100 rounded-lg">
                  <Mail className="w-5 h-5 text-primary flex-shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <p className="text-sm text-gray-700 font-medium mb-1">
                      {t("forgotpassword.checkphone")}
                    </p>
                    <p className="text-xs text-gray-600">
                      {t("forgotpassword.checkdesc")}
                    </p>
                  </div>
                </div>

                <div className="space-y-3">
                  <Button
                    type="submit"
                    className="w-full h-12 bg-primary hover:bg-primary-500 text-white text-sm font-medium rounded-lg shadow-md hover:shadow-lg transition-all duration-300"
                    disabled={loading}
                  >
                    {loading ? (
                      <span className="flex items-center justify-center gap-2">
                        <RefreshCw className="animate-spin h-5 w-5" />
                        {t("forgotpassword.sending")}
                      </span>
                    ) : (
                      <span className="flex items-center justify-center gap-2">
                        <Mail className="h-5 w-5" />
                        {t("forgotpassword.sendresetlink")}
                      </span>
                    )}
                  </Button>

                  <Button
                    type="button"
                    variant="outline"
                    className="w-full h-12 text-sm font-medium border-gray-200 hover:bg-gray-50 rounded-lg transition-all duration-300 bg-transparent"
                    onClick={() => navigate("/login")}
                  >
                    <ArrowLeft className="h-4 w-4 mr-2" />
                    {t("forgotpassword.backtologin")}
                  </Button>
                </div>
              </form>
            </div>
          </div>

          <p className="text-center text-sm text-gray-500 mt-6">
            {t("forgotpassword.remember")}{" "}
            <button
              onClick={() => navigate("/login")}
              className="text-primary hover:text-primary-500 font-medium transition-colors"
            >
              {t("forgotpassword.signin")}
            </button>
          </p>
        </div>
      </div>
    </div>
  );
};

export default ForgotPassword;
