import { useState } from "react";
import { motion } from "motion/react";
import { ArrowLeft, Eye, EyeOff, Mail, Phone, Sun, Moon } from "lucide-react";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { useTheme } from "./ThemeProvider";
import { ImageWithFallback } from "./figma/ImageWithFallback";
import enamelLogo from 'figma:asset/2e2e3fad7673e8eef9a255215dd6ac2cf27cc590.png';

interface SignInPageProps {
  onBack: () => void;
  onSignIn: (credentials: { identifier: string; password: string; loginMethod: 'email' | 'phone' }) => void;
  onGoToSignUp: () => void;
}

export function SignInPage({ onBack, onSignIn, onGoToSignUp }: SignInPageProps) {
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loginMethod, setLoginMethod] = useState<'email' | 'phone'>('phone'); // Default to phone for Nigerian market
  const [errors, setErrors] = useState<any>({});
  const { theme, toggleTheme } = useTheme();

  const validateForm = () => {
    const newErrors: any = {};
    
    if (!identifier.trim()) {
      newErrors.identifier = loginMethod === 'email' ? "Email is required" : "Phone number is required";
    } else if (loginMethod === 'email' && !/\S+@\S+\.\S+/.test(identifier)) {
      newErrors.identifier = "Invalid email format";
    } else if (loginMethod === 'phone' && !/^(\+234|0)[789][01]\d{8}$/.test(identifier.replace(/\s/g, ''))) {
      newErrors.identifier = "Invalid Nigerian phone number";
    }
    
    if (!password) {
      newErrors.password = "Password is required";
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = () => {
    if (validateForm()) {
      onSignIn({ 
        identifier: identifier.trim(), 
        password, 
        loginMethod 
      });
    }
  };

  const handleInputChange = (field: string, value: string) => {
    if (field === 'identifier') {
      setIdentifier(value);
    } else {
      setPassword(value);
    }
    
    if (errors[field]) {
      setErrors((prev: any) => ({ ...prev, [field]: "" }));
    }
  };

  const formatPhoneNumber = (value: string) => {
    // Remove all non-digits
    const digits = value.replace(/\D/g, '');
    
    // Format Nigerian phone number
    if (digits.length <= 4) return digits;
    if (digits.length <= 7) return `${digits.slice(0, 4)} ${digits.slice(4)}`;
    if (digits.length <= 11) return `${digits.slice(0, 4)} ${digits.slice(4, 7)} ${digits.slice(7)}`;
    
    return `${digits.slice(0, 4)} ${digits.slice(4, 7)} ${digits.slice(7, 11)}`;
  };

  return (
    <div className={`min-h-screen ${
      theme === 'dark' 
        ? 'bg-gradient-to-br from-background via-card to-background' 
        : 'bg-gradient-to-br from-blue-50 via-white to-blue-100'
    }`}>
      {/* Header */}
      <div className="bg-card shadow-sm border-b p-4">
        <div className="flex items-center justify-between max-w-7xl mx-auto">
          <div className="flex items-center gap-3">
            <Button variant="ghost" size="sm" onClick={onBack}>
              <ArrowLeft className="w-4 h-4" />
            </Button>
            <div>
              <h1 className="text-xl font-bold text-primary">Welcome Back</h1>
              <p className="text-sm text-muted-foreground">Sign in to your Enamel account</p>
            </div>
          </div>
          
          {/* Theme Toggle */}
          <Button
            variant="ghost"
            size="sm"
            onClick={toggleTheme}
            className="rounded-full"
          >
            {theme === 'dark' ? (
              <Sun className="w-4 h-4" />
            ) : (
              <Moon className="w-4 h-4" />
            )}
          </Button>
        </div>
      </div>

      <div className="max-w-md mx-auto p-4 flex items-center min-h-[calc(100vh-120px)]">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          className="w-full"
        >
          <Card>
            <CardHeader className="text-center space-y-4">
              <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto p-2">
                <ImageWithFallback
                  src={enamelLogo}
                  alt="Enamel Wallets Logo"
                  className="w-full h-full object-contain"
                />
              </div>
              <CardTitle className="text-2xl">Sign In</CardTitle>
            </CardHeader>
            
            <CardContent className="space-y-6">
              {/* Login Method Selection */}
              <div>
                <Label className="text-sm font-medium">Sign in with</Label>
                <Tabs value={loginMethod} onValueChange={(value) => setLoginMethod(value as 'email' | 'phone')} className="mt-2">
                  <TabsList className="grid w-full grid-cols-2">
                    <TabsTrigger value="phone" className="flex items-center gap-2">
                      <Phone className="w-4 h-4" />
                      Phone
                    </TabsTrigger>
                    <TabsTrigger value="email" className="flex items-center gap-2">
                      <Mail className="w-4 h-4" />
                      Email
                    </TabsTrigger>
                  </TabsList>
                </Tabs>
              </div>

              {/* Identifier Input */}
              <div>
                <Label htmlFor="identifier">
                  {loginMethod === 'email' ? 'Email Address' : 'Phone Number'}
                </Label>
                <Input
                  id="identifier"
                  type={loginMethod === 'email' ? 'email' : 'tel'}
                  value={identifier}
                  onChange={(e) => {
                    if (loginMethod === 'phone') {
                      const formatted = formatPhoneNumber(e.target.value);
                      if (formatted.length <= 13) {
                        handleInputChange('identifier', formatted);
                      }
                    } else {
                      handleInputChange('identifier', e.target.value);
                    }
                  }}
                  placeholder={loginMethod === 'email' ? 'Enter your email' : '0803 123 4567'}
                  className={errors.identifier ? "border-destructive" : ""}
                />
                {errors.identifier && (
                  <p className="text-destructive text-sm mt-1">{errors.identifier}</p>
                )}
              </div>

              {/* Password Input */}
              <div>
                <Label htmlFor="password">Password</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    value={password}
                    onChange={(e) => handleInputChange('password', e.target.value)}
                    placeholder="Enter your password"
                    className={errors.password ? "border-destructive" : ""}
                    onKeyPress={(e) => e.key === 'Enter' && handleSubmit()}
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                </div>
                {errors.password && (
                  <p className="text-destructive text-sm mt-1">{errors.password}</p>
                )}
              </div>

              {/* Forgot Password */}
              <div className="text-right">
                <Button variant="link" className="p-0 h-auto text-sm text-primary">
                  Forgot password?
                </Button>
              </div>

              {/* Sign In Button */}
              <Button
                onClick={handleSubmit}
                className="w-full bg-primary hover:bg-primary/90"
                size="lg"
              >
                Sign In
              </Button>

              {/* Divider */}
              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <span className="w-full border-t" />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-card px-2 text-muted-foreground">New to Enamel?</span>
                </div>
              </div>

              {/* Sign Up Link */}
              <Button
                onClick={onGoToSignUp}
                variant="outline"
                className="w-full"
                size="lg"
              >
                Create Account
              </Button>
            </CardContent>
          </Card>

          {/* Marketing Message */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.8, delay: 0.3 }}
            className="text-center mt-8 space-y-2"
          >
            <p className="text-sm text-muted-foreground">
              🏦 Trusted by thousands of Nigerians
            </p>
            <p className="text-xs text-muted-foreground">
              Secure • Fast • Reliable Financial Services
            </p>
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}