import { useState } from "react";
import { motion } from "motion/react";
import { 
  ArrowLeft, 
  Send, 
  User, 
  CreditCard, 
  Check,
  Search,
  Phone,
  Mail,
  AlertCircle
} 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 { formatNaira } from "../utils/currency";
import { toast } from "sonner@2.0.3";
import { useNotifications } from "./NotificationProvider";
import { NotificationService } from "../utils/notifications";

interface P2PTransferProps {
  onBack: () => void;
  spendingBalance: number;
  currentUser: any;
}

interface Recipient {
  id: string;
  firstName: string;
  lastName: string;
  email?: string;
  phone?: string;
  avatar?: string;
}

export function P2PTransfer({ onBack, spendingBalance, currentUser }: P2PTransferProps) {
  const [step, setStep] = useState<'search' | 'confirm' | 'success'>('search');
  const [searchQuery, setSearchQuery] = useState('');
  const [amount, setAmount] = useState('');
  const [note, setNote] = useState('');
  const [selectedRecipient, setSelectedRecipient] = useState<Recipient | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<Recipient[]>([]);
  const { showNotification } = useNotifications();

  // Mock recent recipients
  const recentRecipients: Recipient[] = [
    {
      id: '1',
      firstName: 'Adaora',
      lastName: 'Okafor',
      email: 'adaora.okafor@example.com',
      phone: '+234 803 123 4567'
    },
    {
      id: '2',
      firstName: 'Chidi',
      lastName: 'Eze',
      email: 'chidi.eze@example.com',
      phone: '+234 805 987 6543'
    },
    {
      id: '3',
      firstName: 'Funmi',
      lastName: 'Adebayo',
      email: 'funmi.adebayo@example.com',
      phone: '+234 807 555 0123'
    }
  ];

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    
    setIsLoading(true);
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // Mock search results - in real app this would call the backend
      const mockResults = recentRecipients.filter(recipient => 
        recipient.firstName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        recipient.lastName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        recipient.email?.includes(searchQuery.toLowerCase()) ||
        recipient.phone?.includes(searchQuery)
      );
      
      setSearchResults(mockResults);
    } catch (error) {
      toast.error('Search failed', {
        description: 'Please try again'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelectRecipient = (recipient: Recipient) => {
    setSelectedRecipient(recipient);
    setStep('confirm');
  };

  const handleSendMoney = async () => {
    if (!selectedRecipient || !amount) return;
    
    const transferAmount = parseFloat(amount);
    
    if (transferAmount > spendingBalance) {
      toast.error('Insufficient balance');
      return;
    }
    
    setIsLoading(true);
    
    try {
      // Simulate transfer processing
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Show success notification
      const transferNotification = NotificationService.getTransactionNotification(
        'debit',
        transferAmount,
        spendingBalance - transferAmount
      );
      await showNotification(transferNotification);
      
      setStep('success');
      
      toast.success('Transfer successful!', {
        description: `${formatNaira(transferAmount)} sent to ${selectedRecipient.firstName}`
      });
      
    } catch (error) {
      toast.error('Transfer failed', {
        description: 'Please try again'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const isValidAmount = () => {
    const transferAmount = parseFloat(amount);
    return transferAmount > 0 && transferAmount <= spendingBalance;
  };

  if (step === 'success') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-green-50 via-white to-green-100 dark:from-green-900/20 dark:via-background dark:to-green-900/20 flex items-center justify-center p-4">
        <motion.div
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ type: "spring", stiffness: 200 }}
          className="text-center"
        >
          <div className="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
            <Check className="w-10 h-10 text-white" />
          </div>
          <h2 className="text-2xl font-bold text-secondary mb-2">Transfer Successful!</h2>
          <p className="text-muted-foreground mb-4">
            {formatNaira(parseFloat(amount))} sent to {selectedRecipient?.firstName} {selectedRecipient?.lastName}
          </p>
          <div className="space-y-2">
            <p className="text-sm text-muted-foreground">Transaction ID: TXN{Date.now()}</p>
            <p className="text-sm text-muted-foreground">{new Date().toLocaleString()}</p>
          </div>
          <Button
            onClick={onBack}
            className="mt-6 bg-primary hover:bg-primary/90"
          >
            Back to Dashboard
          </Button>
        </motion.div>
      </div>
    );
  }

  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-7xl mx-auto">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <Send className="w-6 h-6 text-primary" />
          <div>
            <h1 className="text-xl font-bold">Send Money</h1>
            <p className="text-sm text-muted-foreground">Transfer to other Enamel Wallet users</p>
          </div>
        </div>
      </div>

      <div className="max-w-2xl mx-auto p-4 space-y-6">
        {/* Balance Display */}
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <Card className="bg-gradient-to-r from-primary to-primary/80 text-white">
            <CardContent className="p-4">
              <div className="flex justify-between items-center">
                <div>
                  <p className="text-primary-foreground/80 text-sm">Available Balance</p>
                  <p className="text-2xl font-bold">{formatNaira(spendingBalance)}</p>
                </div>
                <CreditCard className="w-8 h-8 text-primary-foreground/60" />
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {step === 'search' && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="space-y-6"
          >
            {/* Search Section */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Search className="w-5 h-5" />
                  Find Recipient
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="search">Email or Phone Number</Label>
                  <div className="flex gap-2">
                    <Input
                      id="search"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      placeholder="Enter email or phone number"
                      onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                    />
                    <Button 
                      onClick={handleSearch}
                      disabled={isLoading || !searchQuery.trim()}
                      className="bg-primary hover:bg-primary/90"
                    >
                      {isLoading ? 'Searching...' : 'Search'}
                    </Button>
                  </div>
                </div>

                {searchResults.length > 0 && (
                  <div className="space-y-2">
                    <Label>Search Results</Label>
                    {searchResults.map((recipient) => (
                      <div
                        key={recipient.id}
                        className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 cursor-pointer"
                        onClick={() => handleSelectRecipient(recipient)}
                      >
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center">
                            <User className="w-5 h-5 text-primary" />
                          </div>
                          <div>
                            <p className="font-medium">{recipient.firstName} {recipient.lastName}</p>
                            <div className="flex items-center gap-4 text-sm text-muted-foreground">
                              {recipient.email && (
                                <div className="flex items-center gap-1">
                                  <Mail className="w-3 h-3" />
                                  {recipient.email}
                                </div>
                              )}
                              {recipient.phone && (
                                <div className="flex items-center gap-1">
                                  <Phone className="w-3 h-3" />
                                  {recipient.phone}
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                        <Button size="sm" variant="outline">
                          Select
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Recent Recipients */}
            <Card>
              <CardHeader>
                <CardTitle>Recent Recipients</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {recentRecipients.slice(0, 3).map((recipient) => (
                    <div
                      key={recipient.id}
                      className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 cursor-pointer"
                      onClick={() => handleSelectRecipient(recipient)}
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-secondary/10 rounded-full flex items-center justify-center">
                          <User className="w-5 h-5 text-secondary" />
                        </div>
                        <div>
                          <p className="font-medium">{recipient.firstName} {recipient.lastName}</p>
                          <p className="text-sm text-muted-foreground">{recipient.phone}</p>
                        </div>
                      </div>
                      <Button size="sm" variant="outline">
                        Send
                      </Button>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}

        {step === 'confirm' && selectedRecipient && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="space-y-6"
          >
            {/* Recipient Info */}
            <Card>
              <CardHeader>
                <CardTitle>Sending to</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
                  <div className="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center">
                    <User className="w-6 h-6 text-primary" />
                  </div>
                  <div>
                    <p className="font-medium">{selectedRecipient.firstName} {selectedRecipient.lastName}</p>
                    <p className="text-sm text-muted-foreground">{selectedRecipient.phone || selectedRecipient.email}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Transfer Details */}
            <Card>
              <CardHeader>
                <CardTitle>Transfer Details</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="amount">Amount</Label>
                  <Input
                    id="amount"
                    type="number"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    placeholder="0.00"
                    min="1"
                    max={spendingBalance}
                  />
                  {amount && parseFloat(amount) > spendingBalance && (
                    <Alert className="mt-2">
                      <AlertCircle className="w-4 h-4" />
                      <AlertDescription>
                        Insufficient balance. Maximum: {formatNaira(spendingBalance)}
                      </AlertDescription>
                    </Alert>
                  )}
                </div>

                <div>
                  <Label htmlFor="note">Note (Optional)</Label>
                  <Input
                    id="note"
                    value={note}
                    onChange={(e) => setNote(e.target.value)}
                    placeholder="What's this for?"
                    maxLength={100}
                  />
                </div>

                {amount && isValidAmount() && (
                  <div className="p-4 bg-muted/50 rounded-lg space-y-2">
                    <div className="flex justify-between">
                      <span>Amount:</span>
                      <span className="font-medium">{formatNaira(parseFloat(amount))}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Fee:</span>
                      <span className="font-medium text-secondary">Free</span>
                    </div>
                    <div className="border-t pt-2 flex justify-between font-bold">
                      <span>Total:</span>
                      <span>{formatNaira(parseFloat(amount))}</span>
                    </div>
                  </div>
                )}

                <div className="flex gap-3">
                  <Button
                    variant="outline"
                    onClick={() => setStep('search')}
                    className="flex-1"
                  >
                    Back
                  </Button>
                  <Button
                    onClick={handleSendMoney}
                    disabled={!isValidAmount() || isLoading}
                    className="flex-1 bg-secondary hover:bg-secondary/90"
                  >
                    {isLoading ? 'Sending...' : `Send ${amount ? formatNaira(parseFloat(amount)) : 'Money'}`}
                  </Button>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}
      </div>
    </div>
  );
}