import { useState } from "react";
import { motion } from "motion/react";
import { ArrowLeft, Eye, EyeOff, Check, Upload, User, Shield, Phone, Mail } 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 { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Alert, AlertDescription } from "./ui/alert";
import { Checkbox } from "./ui/checkbox";
import { useTheme } from "./ThemeProvider";

interface SignUpPageProps {
  onBack: () => void;
  onSignUp: (userData: any) => void;
  onGoToSignIn: () => void;
}

export function SignUpPage({ onBack, onSignUp, onGoToSignIn }: SignUpPageProps) {
  const [step, setStep] = useState(1);
  const [showPassword, setShowPassword] = useState(false);
  const [loginMethod, setLoginMethod] = useState<'email' | 'phone'>('phone'); // Default to phone for Nigerian market
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    password: "",
    confirmPassword: "",
    dateOfBirth: "",
    address: "",
    bvn: "",
    idType: "nin",
    idNumber: "",
    agreeToTerms: false,
    agreeToPrivacy: false
  });
  const [errors, setErrors] = useState<any>({});
  const { theme } = useTheme();

  const validateStep1 = () => {
    const newErrors: any = {};
    
    if (!formData.firstName.trim()) newErrors.firstName = "First name is required";
    if (!formData.lastName.trim()) newErrors.lastName = "Last name is required";
    
    if (loginMethod === 'email') {
      if (!formData.email.trim()) {
        newErrors.email = "Email is required";
      } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
        newErrors.email = "Email is invalid";
      }
    } else {
      if (!formData.phone.trim()) {
        newErrors.phone = "Phone number is required";
      } else if (!/^(\+234|0)[789][01]\d{8}$/.test(formData.phone.replace(/\s/g, ''))) {
        newErrors.phone = "Invalid Nigerian phone number";
      }
    }
    
    if (!formData.password) {
      newErrors.password = "Password is required";
    } else if (formData.password.length < 8) {
      newErrors.password = "Password must be at least 8 characters";
    }
    
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = "Passwords do not match";
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep2 = () => {
    const newErrors: any = {};
    
    if (!formData.dateOfBirth) newErrors.dateOfBirth = "Date of birth is required";
    if (!formData.address.trim()) newErrors.address = "Address is required";
    if (!formData.bvn.trim()) {
      newErrors.bvn = "BVN is required";
    } else if (!/^\d{11}$/.test(formData.bvn)) {
      newErrors.bvn = "BVN must be 11 digits";
    }
    if (!formData.idNumber.trim()) newErrors.idNumber = "ID number is required";
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep3 = () => {
    const newErrors: any = {};
    
    if (!formData.agreeToTerms) newErrors.agreeToTerms = "You must agree to the terms";
    if (!formData.agreeToPrivacy) newErrors.agreeToPrivacy = "You must agree to the privacy policy";
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    let isValid = false;
    
    switch (step) {
      case 1:
        isValid = validateStep1();
        break;
      case 2:
        isValid = validateStep2();
        break;
      case 3:
        isValid = validateStep3();
        break;
    }
    
    if (isValid) {
      if (step < 3) {
        setStep(step + 1);
      } else {
        // Final submission
        const submitData = {
          ...formData,
          loginMethod,
          primaryContact: loginMethod === 'email' ? formData.email : formData.phone
        };
        onSignUp(submitData);
      }
    }
  };

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: 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 gap-3 max-w-7xl mx-auto">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div>
            <h1 className="text-xl font-bold text-primary">Create Enamel Account</h1>
            <p className="text-sm text-muted-foreground">Step {step} of 3</p>
          </div>
        </div>
      </div>

      <div className="max-w-2xl mx-auto p-4">
        {/* Progress Bar */}
        <div className="mb-8">
          <div className="flex justify-between mb-2">
            {[1, 2, 3].map((i) => (
              <Badge 
                key={i}
                variant={i <= step ? "default" : "secondary"}
                className={i <= step ? "bg-primary" : ""}
              >
                {i < step ? <Check className="w-3 h-3" /> : i}
              </Badge>
            ))}
          </div>
          <div className="w-full bg-muted h-2 rounded-full">
            <div 
              className="bg-primary h-2 rounded-full transition-all duration-500"
              style={{ width: `${(step / 3) * 100}%` }}
            />
          </div>
        </div>

        {/* Step 1: Personal Information */}
        {step === 1 && (
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <User className="w-5 h-5 text-primary" />
                  Personal Information
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Login Method Selection */}
                <div>
                  <Label>Primary Contact Method</Label>
                  <Tabs value={loginMethod} onValueChange={(value) => setLoginMethod(value as 'email' | 'phone')}>
                    <TabsList className="grid w-full grid-cols-2">
                      <TabsTrigger value="phone" className="flex items-center gap-2">
                        <Phone className="w-4 h-4" />
                        Phone Number
                      </TabsTrigger>
                      <TabsTrigger value="email" className="flex items-center gap-2">
                        <Mail className="w-4 h-4" />
                        Email Address
                      </TabsTrigger>
                    </TabsList>
                  </Tabs>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="firstName">First Name</Label>
                    <Input
                      id="firstName"
                      value={formData.firstName}
                      onChange={(e) => handleInputChange("firstName", e.target.value)}
                      placeholder="Enter first name"
                      className={errors.firstName ? "border-destructive" : ""}
                    />
                    {errors.firstName && <p className="text-destructive text-sm mt-1">{errors.firstName}</p>}
                  </div>
                  
                  <div>
                    <Label htmlFor="lastName">Last Name</Label>
                    <Input
                      id="lastName"
                      value={formData.lastName}
                      onChange={(e) => handleInputChange("lastName", e.target.value)}
                      placeholder="Enter last name"
                      className={errors.lastName ? "border-destructive" : ""}
                    />
                    {errors.lastName && <p className="text-destructive text-sm mt-1">{errors.lastName}</p>}
                  </div>
                </div>

                {loginMethod === 'email' ? (
                  <div>
                    <Label htmlFor="email">Email Address</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => handleInputChange("email", e.target.value)}
                      placeholder="Enter email address"
                      className={errors.email ? "border-destructive" : ""}
                    />
                    {errors.email && <p className="text-destructive text-sm mt-1">{errors.email}</p>}
                    <p className="text-xs text-muted-foreground mt-1">We'll use this for login and notifications</p>
                  </div>
                ) : (
                  <div>
                    <Label htmlFor="phone">Phone Number</Label>
                    <Input
                      id="phone"
                      value={formData.phone}
                      onChange={(e) => {
                        const formatted = formatPhoneNumber(e.target.value);
                        if (formatted.length <= 13) { // Max length for formatted Nigerian number
                          handleInputChange("phone", formatted);
                        }
                      }}
                      placeholder="0803 123 4567"
                      className={errors.phone ? "border-destructive" : ""}
                    />
                    {errors.phone && <p className="text-destructive text-sm mt-1">{errors.phone}</p>}
                    <p className="text-xs text-muted-foreground mt-1">We'll use this for login and SMS notifications</p>
                  </div>
                )}

                {/* Always collect the other contact method as secondary */}
                {loginMethod === 'phone' && (
                  <div>
                    <Label htmlFor="email">Email Address (Optional)</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => handleInputChange("email", e.target.value)}
                      placeholder="Enter email for additional notifications"
                    />
                  </div>
                )}

                {loginMethod === 'email' && (
                  <div>
                    <Label htmlFor="phone">Phone Number (Optional)</Label>
                    <Input
                      id="phone"
                      value={formData.phone}
                      onChange={(e) => {
                        const formatted = formatPhoneNumber(e.target.value);
                        if (formatted.length <= 13) {
                          handleInputChange("phone", formatted);
                        }
                      }}
                      placeholder="0803 123 4567"
                    />
                  </div>
                )}

                <div>
                  <Label htmlFor="password">Password</Label>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      value={formData.password}
                      onChange={(e) => handleInputChange("password", e.target.value)}
                      placeholder="Create a strong password"
                      className={errors.password ? "border-destructive" : ""}
                    />
                    <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>

                <div>
                  <Label htmlFor="confirmPassword">Confirm Password</Label>
                  <Input
                    id="confirmPassword"
                    type="password"
                    value={formData.confirmPassword}
                    onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
                    placeholder="Confirm your password"
                    className={errors.confirmPassword ? "border-destructive" : ""}
                  />
                  {errors.confirmPassword && <p className="text-destructive text-sm mt-1">{errors.confirmPassword}</p>}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}

        {/* Step 2: KYC Information */}
        {step === 2 && (
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Shield className="w-5 h-5 text-primary" />
                  Identity Verification (KYC)
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Alert>
                  <Shield className="w-4 h-4" />
                  <AlertDescription>
                    This information is required for regulatory compliance and account security.
                  </AlertDescription>
                </Alert>

                <div>
                  <Label htmlFor="dateOfBirth">Date of Birth</Label>
                  <Input
                    id="dateOfBirth"
                    type="date"
                    value={formData.dateOfBirth}
                    onChange={(e) => handleInputChange("dateOfBirth", e.target.value)}
                    className={errors.dateOfBirth ? "border-destructive" : ""}
                  />
                  {errors.dateOfBirth && <p className="text-destructive text-sm mt-1">{errors.dateOfBirth}</p>}
                </div>

                <div>
                  <Label htmlFor="address">Home Address</Label>
                  <Input
                    id="address"
                    value={formData.address}
                    onChange={(e) => handleInputChange("address", e.target.value)}
                    placeholder="Enter your full address"
                    className={errors.address ? "border-destructive" : ""}
                  />
                  {errors.address && <p className="text-destructive text-sm mt-1">{errors.address}</p>}
                </div>

                <div>
                  <Label htmlFor="bvn">Bank Verification Number (BVN)</Label>
                  <Input
                    id="bvn"
                    value={formData.bvn}
                    onChange={(e) => {
                      const value = e.target.value.replace(/\D/g, '').slice(0, 11);
                      handleInputChange("bvn", value);
                    }}
                    placeholder="Enter your 11-digit BVN"
                    className={errors.bvn ? "border-destructive" : ""}
                    maxLength={11}
                  />
                  {errors.bvn && <p className="text-destructive text-sm mt-1">{errors.bvn}</p>}
                  <p className="text-xs text-muted-foreground mt-1">Required by Nigerian banking regulations</p>
                </div>

                <div>
                  <Label htmlFor="idType">Government ID Type</Label>
                  <select
                    id="idType"
                    value={formData.idType}
                    onChange={(e) => handleInputChange("idType", e.target.value)}
                    className="w-full p-2 border border-input rounded-md bg-background"
                  >
                    <option value="nin">National Identity Number (NIN)</option>
                    <option value="drivers_license">Driver's License</option>
                    <option value="international_passport">International Passport</option>
                    <option value="voters_card">Voter's Card</option>
                  </select>
                </div>

                <div>
                  <Label htmlFor="idNumber">ID Number</Label>
                  <Input
                    id="idNumber"
                    value={formData.idNumber}
                    onChange={(e) => handleInputChange("idNumber", e.target.value)}
                    placeholder="Enter your ID number"
                    className={errors.idNumber ? "border-destructive" : ""}
                  />
                  {errors.idNumber && <p className="text-destructive text-sm mt-1">{errors.idNumber}</p>}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}

        {/* Step 3: Terms & Conditions */}
        {step === 3 && (
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Check className="w-5 h-5 text-primary" />
                  Terms & Privacy
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Alert>
                  <Shield className="w-4 h-4" />
                  <AlertDescription>
                    Please review and accept our terms to complete your account setup.
                  </AlertDescription>
                </Alert>

                <div className="space-y-4">
                  <div className="flex items-start space-x-3">
                    <Checkbox
                      id="agreeToTerms"
                      checked={formData.agreeToTerms}
                      onCheckedChange={(checked) => handleInputChange("agreeToTerms", checked)}
                      className={errors.agreeToTerms ? "border-destructive" : ""}
                    />
                    <div className="space-y-1">
                      <Label htmlFor="agreeToTerms" className="text-sm font-medium leading-none">
                        I agree to the Terms and Conditions
                      </Label>
                      <p className="text-xs text-muted-foreground">
                        By checking this box, you agree to our terms of service and user agreement.
                      </p>
                    </div>
                  </div>
                  {errors.agreeToTerms && <p className="text-destructive text-sm">{errors.agreeToTerms}</p>}

                  <div className="flex items-start space-x-3">
                    <Checkbox
                      id="agreeToPrivacy"
                      checked={formData.agreeToPrivacy}
                      onCheckedChange={(checked) => handleInputChange("agreeToPrivacy", checked)}
                      className={errors.agreeToPrivacy ? "border-destructive" : ""}
                    />
                    <div className="space-y-1">
                      <Label htmlFor="agreeToPrivacy" className="text-sm font-medium leading-none">
                        I agree to the Privacy Policy
                      </Label>
                      <p className="text-xs text-muted-foreground">
                        We will handle your personal data according to our privacy policy.
                      </p>
                    </div>
                  </div>
                  {errors.agreeToPrivacy && <p className="text-destructive text-sm">{errors.agreeToPrivacy}</p>}
                </div>

                <div className="bg-muted p-4 rounded-lg">
                  <h4 className="font-medium mb-2">Account Summary</h4>
                  <div className="text-sm space-y-1">
                    <p><strong>Name:</strong> {formData.firstName} {formData.lastName}</p>
                    <p><strong>Primary Contact:</strong> {loginMethod === 'email' ? formData.email : formData.phone}</p>
                    {loginMethod === 'email' && formData.phone && (
                      <p><strong>Phone:</strong> {formData.phone}</p>
                    )}
                    {loginMethod === 'phone' && formData.email && (
                      <p><strong>Email:</strong> {formData.email}</p>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}

        {/* Navigation Buttons */}
        <div className="flex justify-between items-center mt-8 mb-8">
          <Button
            variant="outline"
            onClick={() => {
              if (step > 1) {
                setStep(step - 1);
              } else {
                onBack();
              }
            }}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            {step > 1 ? "Previous" : "Back"}
          </Button>

          <Button
            onClick={handleNext}
            className="px-8"
            disabled={
              (step === 1 && (!formData.firstName || !formData.lastName)) ||
              (step === 2 && (!formData.dateOfBirth || !formData.address || !formData.bvn || !formData.idNumber)) ||
              (step === 3 && (!formData.agreeToTerms || !formData.agreeToPrivacy))
            }
          >
            {step === 3 ? "Create Account" : "Next"}
          </Button>
        </div>

        {/* Sign In Link */}
        <div className="text-center">
          <p className="text-sm text-muted-foreground">
            Already have an account?{" "}
            <button
              onClick={onGoToSignIn}
              className="text-primary hover:underline font-medium"
            >
              Sign in here
            </button>
          </p>
        </div>
      </div>
    </div>
  );
}