import { useState } from "react";
import { ArrowLeft, Mail, Lock, Eye, EyeOff, User, Phone } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Link, Navigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";

const MyAccount = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const { login, isAuthenticated } = useAuth();
  const { toast } = useToast();

  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  const validateGhanaPhone = (phoneNumber: string): boolean => {
    // Remove spaces and dashes
    const cleaned = phoneNumber.replace(/[\s-]/g, '');
    
    // Ghana phone number patterns:
    // 0XX XXX XXXX (10 digits starting with 0)
    // 233XX XXX XXXX (12 digits starting with 233)
    // +233XX XXX XXXX (13 chars starting with +233)
    
    const patterns = [
      /^0[2-5][0-9]{8}$/, // 0XX XXX XXXX
      /^233[2-5][0-9]{8}$/, // 233XX XXX XXXX
      /^\+233[2-5][0-9]{8}$/ // +233XX XXX XXXX
    ];
    
    return patterns.some(pattern => pattern.test(cleaned));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) {
      toast({
        title: "Error",
        description: "Please fill in all fields.",
        variant: "destructive",
      });
      return;
    }
    if (!isLogin && !name) {
      toast({
        title: "Error",
        description: "Please enter your name.",
        variant: "destructive",
      });
      return;
    }
    if (!isLogin && !phone) {
      toast({
        title: "Error",
        description: "Please enter your phone number.",
        variant: "destructive",
      });
      return;
    }
    if (!isLogin && !validateGhanaPhone(phone)) {
      toast({
        title: "Invalid Phone Number",
        description: "Please enter a valid Ghana phone number (e.g., 0241234567 or +233241234567).",
        variant: "destructive",
      });
      return;
    }
    login(email, name || undefined);
    toast({
      title: isLogin ? "Welcome back!" : "Account created!",
      description: "You have been logged in successfully.",
    });
  };

  return (
    <div className="min-h-screen bg-muted/50 flex flex-col items-center justify-center px-4">
      <Link
        to="/"
        className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors mb-8"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to Home
      </Link>

      <Card className="w-full max-w-md shadow-lg border-border/50">
        <CardContent className="p-8">
          {/* Logo */}
          <div className="flex items-center justify-center gap-2 mb-6">
            <div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center">
              <span className="text-primary-foreground font-bold text-lg">¥</span>
            </div>
            <div>
              <span className="font-bold text-foreground text-xl tracking-tight">BUY RMB</span>
              <span className="block text-[9px] text-muted-foreground tracking-[0.2em] uppercase -mt-1">
                Fast.Safe.Reliable
              </span>
            </div>
          </div>

          <h1 className="text-2xl font-bold text-foreground text-center">
            {isLogin ? "Welcome Back" : "Create Account"}
          </h1>
          <p className="text-muted-foreground text-center text-sm mt-1 mb-6">
            {isLogin ? "Login to manage your exchanges" : "Sign up to start exchanging"}
          </p>

          <form onSubmit={handleSubmit} className="space-y-4">
            {!isLogin && (
              <>
                <div>
                  <label className="text-sm text-muted-foreground mb-1.5 block">Full Name</label>
                  <div className="relative">
                    <Input
                      type="text"
                      placeholder="John Doe"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="pl-10 h-11 bg-muted/50 border-border"
                      required
                    />
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  </div>
                </div>
                <div>
                  <label className="text-sm text-muted-foreground mb-1.5 block">
                    Phone Number <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <Input
                      type="tel"
                      placeholder="0241234567 or +233241234567"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      className="pl-10 h-11 bg-muted/50 border-border"
                      required
                    />
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    Enter a valid Ghana phone number
                  </p>
                </div>
              </>
            )}

            <div>
              <label className="text-sm text-muted-foreground mb-1.5 block">Email</label>
              <div className="relative">
                <Input
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10 h-11 bg-muted/50 border-border"
                />
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              </div>
            </div>

            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label className="text-sm text-muted-foreground">Password</label>
                {isLogin && (
                  <button type="button" className="text-xs text-primary hover:underline">
                    Forgot password?
                  </button>
                )}
              </div>
              <div className="relative">
                <Input
                  type={showPassword ? "text" : "password"}
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pl-10 pr-10 h-11 bg-muted/50 border-border"
                />
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <Button type="submit" className="w-full h-11 text-base font-semibold mt-2">
              {isLogin ? "Login" : "Sign Up"}
            </Button>
          </form>

          <p className="text-center text-sm text-muted-foreground mt-6">
            {isLogin ? "Don't have an account?" : "Already have an account?"}{" "}
            <button
              onClick={() => setIsLogin(!isLogin)}
              className="text-primary font-medium hover:underline"
            >
              {isLogin ? "Sign Up" : "Login"}
            </button>
          </p>
        </CardContent>
      </Card>
    </div>
  );
};

export default MyAccount;
