import { useState, useEffect } from "react";
import { motion } from "motion/react";
import { 
  User, 
  Shield, 
  CreditCard, 
  Building, 
  Check,
  AlertCircle,
  FileText,
  Camera,
  Phone,
  Mail,
  ArrowLeft,
  ArrowRight
} 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 { Alert, AlertDescription } from "./ui/alert";
import { Progress } from "./ui/progress";
import { toast } from "sonner@2.0.3";

interface AccountSetupProps {
  user: any;
  onComplete: () => void;
  onBack: () => void;
}

interface SetupStep {
  id: string;
  title: string;
  description: string;
  icon: any;
  required: boolean;
  completed: boolean;
}

export function AccountSetup({ user, onComplete, onBack }: AccountSetupProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    // KYC Information
    bvn: '',
    nin: '',
    dateOfBirth: '',
    address: '',
    occupation: '',
    
    // Bank Account
    bankCode: '',
    accountNumber: '',
    accountName: '',
    
    // Verification
    phoneVerificationCode: '',
    emailVerificationCode: '',
    
    // Documents
    profilePhoto: null as File | null,
    idDocument: null as File | null,
    addressProof: null as File | null,
  });

  const [steps, setSteps] = useState<SetupStep[]>([
    {
      id: 'kyc',
      title: 'Identity Verification',
      description: 'Verify your identity with BVN and NIN',
      icon: Shield,
      required: true,
      completed: false
    },
    {
      id: 'bank',
      title: 'Link Bank Account',
      description: 'Connect your primary bank account',
      icon: Building,
      required: true,
      completed: false
    },
    {
      id: 'verification',
      title: 'Contact Verification',
      description: 'Verify your phone and email',
      icon: Phone,
      required: true,
      completed: false
    },
    {
      id: 'documents',
      title: 'Document Upload',
      description: 'Upload required documents',
      icon: FileText,
      required: false,
      completed: false
    },
    {
      id: 'wallets',
      title: 'Setup Wallets',
      description: 'Initialize your savings wallets',
      icon: CreditCard,
      required: true,
      completed: false
    }
  ]);

  const Nigerian_Banks = [
    { code: '044', name: 'Access Bank' },
    { code: '014', name: 'Afribank' },
    { code: '023', name: 'Citibank' },
    { code: '050', name: 'Ecobank' },
    { code: '040', name: 'Equitorial Trust Bank' },
    { code: '011', name: 'First Bank' },
    { code: '214', name: 'First City Monument Bank' },
    { code: '070', name: 'Fidelity Bank' },
    { code: '058', name: 'Guaranty Trust Bank' },
    { code: '030', name: 'Heritage Bank' },
    { code: '301', name: 'Jaiz Bank' },
    { code: '082', name: 'Keystone Bank' },
    { code: '084', name: 'Polaris Bank' },
    { code: '076', name: 'Skye Bank' },
    { code: '221', name: 'Stanbic IBTC Bank' },
    { code: '068', name: 'Standard Chartered Bank' },
    { code: '232', name: 'Sterling Bank' },
    { code: '032', name: 'Union Bank' },
    { code: '033', name: 'United Bank For Africa' },
    { code: '215', name: 'Unity Bank' },
    { code: '035', name: 'Wema Bank' },
    { code: '057', name: 'Zenith Bank' }
  ];

  const completedSteps = steps.filter(step => step.completed).length;
  const progressPercentage = (completedSteps / steps.length) * 100;

  const handleStepComplete = (stepId: string) => {
    setSteps(prev => prev.map(step => 
      step.id === stepId ? { ...step, completed: true } : step
    ));
  };

  const handleVerifyBVN = async () => {
    if (!formData.bvn || formData.bvn.length !== 11) {
      toast.error("Please enter a valid 11-digit BVN");
      return;
    }

    setIsLoading(true);
    try {
      // Simulate BVN verification API call
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Mock successful verification
      toast.success("BVN verified successfully!");
      handleStepComplete('kyc');
      setCurrentStep(1);
    } catch (error) {
      toast.error("BVN verification failed. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerifyBankAccount = async () => {
    if (!formData.bankCode || !formData.accountNumber) {
      toast.error("Please fill in all bank details");
      return;
    }

    setIsLoading(true);
    try {
      // Simulate bank account verification
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // Mock account name resolution
      setFormData(prev => ({ 
        ...prev, 
        accountName: `${user?.firstName} ${user?.lastName}` 
      }));
      
      toast.success("Bank account verified successfully!");
      handleStepComplete('bank');
      setCurrentStep(2);
    } catch (error) {
      toast.error("Bank account verification failed");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSendVerificationCodes = async () => {
    setIsLoading(true);
    try {
      // Simulate sending verification codes
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      toast.success("Verification codes sent to your phone and email!");
    } catch (error) {
      toast.error("Failed to send verification codes");
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerifyContacts = async () => {
    if (!formData.phoneVerificationCode || !formData.emailVerificationCode) {
      toast.error("Please enter both verification codes");
      return;
    }

    setIsLoading(true);
    try {
      // Simulate code verification
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      toast.success("Phone and email verified successfully!");
      handleStepComplete('verification');
      setCurrentStep(3);
    } catch (error) {
      toast.error("Verification codes are incorrect");
    } finally {
      setIsLoading(false);
    }
  };

  const handleDocumentUpload = async () => {
    // Documents are optional, so we can skip
    handleStepComplete('documents');
    setCurrentStep(4);
  };

  const handleCreateWallets = async () => {
    setIsLoading(true);
    try {
      // Simulate wallet creation
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Create default wallets
      const defaultWallets = [
        'Daily Savings',
        'Property Savings', 
        'Spending Wallet'
      ];
      
      toast.success("Default wallets created successfully!");
      handleStepComplete('wallets');
      
      // Complete setup
      setTimeout(() => {
        onComplete();
      }, 1000);
    } catch (error) {
      toast.error("Failed to create wallets");
    } finally {
      setIsLoading(false);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0: // KYC
        return (
          <div className="space-y-6">
            <div>
              <Label htmlFor="bvn">Bank Verification Number (BVN)</Label>
              <Input
                id="bvn"
                value={formData.bvn}
                onChange={(e) => setFormData(prev => ({ ...prev, bvn: e.target.value }))}
                placeholder="Enter your 11-digit BVN"
                maxLength={11}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Your BVN helps us verify your identity securely
              </p>
            </div>

            <div>
              <Label htmlFor="nin">National Identification Number (NIN)</Label>
              <Input
                id="nin"
                value={formData.nin}
                onChange={(e) => setFormData(prev => ({ ...prev, nin: e.target.value }))}
                placeholder="Enter your 11-digit NIN"
                maxLength={11}
              />
            </div>

            <div>
              <Label htmlFor="dateOfBirth">Date of Birth</Label>
              <Input
                id="dateOfBirth"
                type="date"
                value={formData.dateOfBirth}
                onChange={(e) => setFormData(prev => ({ ...prev, dateOfBirth: e.target.value }))}
              />
            </div>

            <Button 
              onClick={handleVerifyBVN}
              disabled={isLoading || !formData.bvn}
              className="w-full"
            >
              {isLoading ? 'Verifying...' : 'Verify Identity'}
            </Button>
          </div>
        );

      case 1: // Bank Account
        return (
          <div className="space-y-6">
            <div>
              <Label htmlFor="bankCode">Select Your Bank</Label>
              <select
                id="bankCode"
                value={formData.bankCode}
                onChange={(e) => setFormData(prev => ({ ...prev, bankCode: e.target.value }))}
                className="w-full p-2 border rounded-md"
              >
                <option value="">Select a bank</option>
                {Nigerian_Banks.map(bank => (
                  <option key={bank.code} value={bank.code}>
                    {bank.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <Label htmlFor="accountNumber">Account Number</Label>
              <Input
                id="accountNumber"
                value={formData.accountNumber}
                onChange={(e) => setFormData(prev => ({ ...prev, accountNumber: e.target.value }))}
                placeholder="Enter your 10-digit account number"
                maxLength={10}
              />
            </div>

            {formData.accountName && (
              <Alert>
                <Check className="w-4 h-4" />
                <AlertDescription>
                  Account Name: <strong>{formData.accountName}</strong>
                </AlertDescription>
              </Alert>
            )}

            <Button 
              onClick={handleVerifyBankAccount}
              disabled={isLoading || !formData.bankCode || !formData.accountNumber}
              className="w-full"
            >
              {isLoading ? 'Verifying...' : 'Verify Bank Account'}
            </Button>
          </div>
        );

      case 2: // Contact Verification
        return (
          <div className="space-y-6">
            <Alert>
              <Phone className="w-4 h-4" />
              <AlertDescription>
                We'll send verification codes to {user?.phone} and {user?.email}
              </AlertDescription>
            </Alert>

            <Button 
              onClick={handleSendVerificationCodes}
              disabled={isLoading}
              variant="outline"
              className="w-full"
            >
              {isLoading ? 'Sending...' : 'Send Verification Codes'}
            </Button>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="phoneCode">Phone Code</Label>
                <Input
                  id="phoneCode"
                  value={formData.phoneVerificationCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, phoneVerificationCode: e.target.value }))}
                  placeholder="Enter SMS code"
                  maxLength={6}
                />
              </div>

              <div>
                <Label htmlFor="emailCode">Email Code</Label>
                <Input
                  id="emailCode"
                  value={formData.emailVerificationCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, emailVerificationCode: e.target.value }))}
                  placeholder="Enter email code"
                  maxLength={6}
                />
              </div>
            </div>

            <Button 
              onClick={handleVerifyContacts}
              disabled={isLoading || !formData.phoneVerificationCode || !formData.emailVerificationCode}
              className="w-full"
            >
              {isLoading ? 'Verifying...' : 'Verify Contacts'}
            </Button>
          </div>
        );

      case 3: // Documents
        return (
          <div className="space-y-6">
            <Alert>
              <FileText className="w-4 h-4" />
              <AlertDescription>
                Document upload is optional but recommended for higher transaction limits
              </AlertDescription>
            </Alert>

            <div className="grid grid-cols-1 gap-4">
              <div>
                <Label>Profile Photo</Label>
                <Input
                  type="file"
                  accept="image/*"
                  onChange={(e) => setFormData(prev => ({ 
                    ...prev, 
                    profilePhoto: e.target.files?.[0] || null 
                  }))}
                />
              </div>

              <div>
                <Label>ID Document (Driver's License, Passport, etc.)</Label>
                <Input
                  type="file"
                  accept="image/*,application/pdf"
                  onChange={(e) => setFormData(prev => ({ 
                    ...prev, 
                    idDocument: e.target.files?.[0] || null 
                  }))}
                />
              </div>

              <div>
                <Label>Address Proof (Utility Bill, Bank Statement)</Label>
                <Input
                  type="file"
                  accept="image/*,application/pdf"
                  onChange={(e) => setFormData(prev => ({ 
                    ...prev, 
                    addressProof: e.target.files?.[0] || null 
                  }))}
                />
              </div>
            </div>

            <div className="flex gap-3">
              <Button 
                onClick={handleDocumentUpload}
                variant="outline"
                className="flex-1"
              >
                Skip for Now
              </Button>
              <Button 
                onClick={handleDocumentUpload}
                className="flex-1"
              >
                Upload Documents
              </Button>
            </div>
          </div>
        );

      case 4: // Wallets
        return (
          <div className="space-y-6">
            <div className="text-center">
              <CreditCard className="w-16 h-16 mx-auto text-primary mb-4" />
              <h3 className="text-xl font-semibold mb-2">Setup Complete!</h3>
              <p className="text-muted-foreground">
                We'll create your default wallets to get you started
              </p>
            </div>

            <div className="space-y-3">
              {[
                { name: 'Spending Wallet', desc: 'For daily transactions and bills' },
                { name: 'Daily Savings', desc: 'Automated daily savings' },
                { name: 'Property Savings', desc: 'Long-term property investment' }
              ].map((wallet, index) => (
                <div key={index} className="flex items-center gap-3 p-3 border rounded-lg">
                  <CreditCard className="w-5 h-5 text-primary" />
                  <div>
                    <p className="font-medium">{wallet.name}</p>
                    <p className="text-sm text-muted-foreground">{wallet.desc}</p>
                  </div>
                  <Check className="w-5 h-5 text-secondary ml-auto" />
                </div>
              ))}
            </div>

            <Button 
              onClick={handleCreateWallets}
              disabled={isLoading}
              className="w-full"
            >
              {isLoading ? 'Creating Wallets...' : 'Create My Wallets'}
            </Button>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-100 dark:from-background dark:via-card dark:to-background">
      {/* Header */}
      <div className="bg-card shadow-sm border-b p-4">
        <div className="flex items-center gap-3 max-w-4xl mx-auto">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div>
            <h1 className="text-xl font-bold">Account Setup</h1>
            <p className="text-sm text-muted-foreground">Complete your profile to access all features</p>
          </div>
        </div>
      </div>

      <div className="max-w-4xl mx-auto p-4 space-y-6">
        {/* Progress */}
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-card rounded-lg p-6 shadow-sm"
        >
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Setup Progress</h2>
            <Badge variant="secondary">{completedSteps}/{steps.length} Complete</Badge>
          </div>
          <Progress value={progressPercentage} className="mb-4" />
          
          <div className="grid grid-cols-5 gap-2">
            {steps.map((step, index) => (
              <div
                key={step.id}
                className={`flex flex-col items-center p-2 rounded-lg transition-colors ${
                  step.completed 
                    ? 'bg-secondary text-white' 
                    : index === currentStep 
                      ? 'bg-primary text-white' 
                      : 'bg-muted'
                }`}
              >
                <step.icon className="w-5 h-5 mb-1" />
                <span className="text-xs text-center">{step.title}</span>
              </div>
            ))}
          </div>
        </motion.div>

        {/* Current Step */}
        <motion.div
          key={currentStep}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Card className="shadow-lg">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center">
                  {React.createElement(steps[currentStep]?.icon, { className: "w-6 h-6 text-primary" })}
                </div>
                <div>
                  <CardTitle>{steps[currentStep]?.title}</CardTitle>
                  <p className="text-muted-foreground">{steps[currentStep]?.description}</p>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {renderStepContent()}
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  );
}