import { useState } from "react";
import { motion } from "motion/react";
import { 
  ArrowLeft, 
  Smartphone, 
  Zap, 
  Tv, 
  Wifi, 
  Car,
  Home,
  CreditCard,
  Check
} 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 { useNotifications } from "./NotificationProvider";
import { NotificationService } from "../utils/notifications";
import { formatNaira } from "../utils/currency";

interface UtilityPaymentsProps {
  onBack: () => void;
  spendingBalance: number;
}

export function UtilityPayments({ onBack, spendingBalance = 25000.75 }: UtilityPaymentsProps) {
  const [activeTab, setActiveTab] = useState("airtime");
  const [selectedProvider, setSelectedProvider] = useState("");
  const [formData, setFormData] = useState({
    phoneNumber: "",
    amount: "",
    meterNumber: "",
    accountNumber: "",
    package: ""
  });
  const [isProcessing, setIsProcessing] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const { showNotification } = useNotifications();

  const services = {
    airtime: {
      title: "Airtime Top-up",
      icon: Smartphone,
      providers: ["MTN", "Airtel", "Glo", "9mobile"],
      quickAmounts: [100, 200, 500, 1000, 2000, 5000]
    },
    data: {
      title: "Data Bundles",
      icon: Wifi,
      providers: ["MTN", "Airtel", "Glo", "9mobile"],
      packages: {
        MTN: [
          { name: "350MB - 1 Day", price: 100 },
          { name: "1GB - 7 Days", price: 300 },
          { name: "2GB - 30 Days", price: 500 },
          { name: "5GB - 30 Days", price: 1200 },
          { name: "10GB - 30 Days", price: 2000 }
        ],
        Airtel: [
          { name: "500MB - 1 Day", price: 100 },
          { name: "1.5GB - 7 Days", price: 300 },
          { name: "3GB - 30 Days", price: 500 },
          { name: "6GB - 30 Days", price: 1200 },
          { name: "12GB - 30 Days", price: 2000 }
        ]
      }
    },
    electricity: {
      title: "Electricity Bills",
      icon: Zap,
      providers: ["EKEDC", "IKEDC", "AEDC", "PHEDC", "KEDCO", "YEDC"],
      quickAmounts: [1000, 2000, 5000, 10000, 15000, 20000]
    },
    cable: {
      title: "Cable TV",
      icon: Tv,
      providers: ["DSTV", "GOTV", "Startimes"],
      packages: {
        DSTV: [
          { name: "Access", price: 2000 },
          { name: "Family", price: 4000 },
          { name: "Compact", price: 6800 },
          { name: "Compact Plus", price: 10500 },
          { name: "Premium", price: 18400 }
        ],
        GOTV: [
          { name: "Smallie", price: 900 },
          { name: "Jinja", price: 1900 },
          { name: "Jolli", price: 2800 },
          { name: "Max", price: 4150 }
        ]
      }
    }
  };

  const handleQuickAmount = (amount: number) => {
    setFormData(prev => ({ ...prev, amount: amount.toString() }));
  };

  const handlePackageSelect = (packageItem: any) => {
    setFormData(prev => ({ 
      ...prev, 
      package: packageItem.name,
      amount: packageItem.price.toString()
    }));
  };

  const handlePayment = async () => {
    setIsProcessing(true);
    
    try {
      // Simulate payment processing
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const amount = parseFloat(formData.amount);
      const serviceTitle = services[activeTab as keyof typeof services]?.title;
      
      // Show success notification
      const billPaymentNotification = NotificationService.getBillPaymentNotification(
        `${serviceTitle} (${selectedProvider})`,
        amount
      );
      await showNotification(billPaymentNotification);
      
      setIsProcessing(false);
      setShowSuccess(true);
      
      // Reset form after 3 seconds
      setTimeout(() => {
        setShowSuccess(false);
        setFormData({
          phoneNumber: "",
          amount: "",
          meterNumber: "",
          accountNumber: "",
          package: ""
        });
        setSelectedProvider("");
      }, 3000);
    } catch (error) {
      console.error("Payment error:", error);
      setIsProcessing(false);
    }
  };

  const canProceed = () => {
    const amount = parseFloat(formData.amount);
    return amount > 0 && amount <= spendingBalance && selectedProvider;
  };

  if (showSuccess) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-green-50 via-white to-green-100 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-green-500 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-green-800 mb-2">Payment Successful!</h2>
          <p className="text-green-600 mb-4">Your {services[activeTab as keyof typeof services]?.title} payment has been processed.</p>
          <p className="text-sm text-gray-600">Amount: {formatNaira(parseFloat(formData.amount))}</p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-100">
      {/* Header */}
      <div className="bg-white 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>
          <CreditCard className="w-6 h-6 text-blue-600" />
          <div>
            <h1 className="text-xl font-bold">Pay Bills</h1>
            <p className="text-sm text-gray-600">Airtime, data, electricity and more</p>
          </div>
        </div>
      </div>

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

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="airtime" className="flex items-center gap-2">
              <Smartphone className="w-4 h-4" />
              Airtime
            </TabsTrigger>
            <TabsTrigger value="data" className="flex items-center gap-2">
              <Wifi className="w-4 h-4" />
              Data
            </TabsTrigger>
            <TabsTrigger value="electricity" className="flex items-center gap-2">
              <Zap className="w-4 h-4" />
              Electricity
            </TabsTrigger>
            <TabsTrigger value="cable" className="flex items-center gap-2">
              <Tv className="w-4 h-4" />
              Cable TV
            </TabsTrigger>
          </TabsList>

          {/* Airtime Tab */}
          <TabsContent value="airtime" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Smartphone className="w-5 h-5" />
                    Airtime Top-up
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Network Selection */}
                  <div>
                    <Label>Select Network</Label>
                    <div className="grid grid-cols-4 gap-2 mt-2">
                      {services.airtime.providers.map((provider) => (
                        <Button
                          key={provider}
                          variant={selectedProvider === provider ? "default" : "outline"}
                          onClick={() => setSelectedProvider(provider)}
                          className="h-12"
                        >
                          {provider}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Phone Number */}
                  <div>
                    <Label htmlFor="phoneNumber">Phone Number</Label>
                    <Input
                      id="phoneNumber"
                      value={formData.phoneNumber}
                      onChange={(e) => setFormData(prev => ({ ...prev, phoneNumber: e.target.value }))}
                      placeholder="08012345678"
                      maxLength={11}
                    />
                  </div>

                  {/* Quick Amounts */}
                  <div>
                    <Label>Quick Amounts</Label>
                    <div className="grid grid-cols-3 gap-2 mt-2">
                      {services.airtime.quickAmounts.map((amount) => (
                        <Button
                          key={amount}
                          variant="outline"
                          onClick={() => handleQuickAmount(amount)}
                          className="h-12"
                        >
                          {formatNaira(amount)}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Custom Amount */}
                  <div>
                    <Label htmlFor="amount">Amount</Label>
                    <Input
                      id="amount"
                      type="number"
                      value={formData.amount}
                      onChange={(e) => setFormData(prev => ({ ...prev, amount: e.target.value }))}
                      placeholder="Enter amount"
                      min="50"
                      max={spendingBalance}
                    />
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* Data Tab */}
          <TabsContent value="data" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Wifi className="w-5 h-5" />
                    Data Bundles
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Network Selection */}
                  <div>
                    <Label>Select Network</Label>
                    <div className="grid grid-cols-4 gap-2 mt-2">
                      {services.data.providers.map((provider) => (
                        <Button
                          key={provider}
                          variant={selectedProvider === provider ? "default" : "outline"}
                          onClick={() => setSelectedProvider(provider)}
                          className="h-12"
                        >
                          {provider}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Phone Number */}
                  <div>
                    <Label htmlFor="phoneNumber">Phone Number</Label>
                    <Input
                      id="phoneNumber"
                      value={formData.phoneNumber}
                      onChange={(e) => setFormData(prev => ({ ...prev, phoneNumber: e.target.value }))}
                      placeholder="08012345678"
                      maxLength={11}
                    />
                  </div>

                  {/* Data Packages */}
                  {selectedProvider && services.data.packages[selectedProvider as keyof typeof services.data.packages] && (
                    <div>
                      <Label>Select Data Package</Label>
                      <div className="grid gap-2 mt-2">
                        {services.data.packages[selectedProvider as keyof typeof services.data.packages].map((pkg, index) => (
                          <Button
                            key={index}
                            variant={formData.package === pkg.name ? "default" : "outline"}
                            onClick={() => handlePackageSelect(pkg)}
                            className="justify-between h-auto p-3"
                          >
                            <span>{pkg.name}</span>
                            <Badge>{formatNaira(pkg.price)}</Badge>
                          </Button>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* Electricity Tab */}
          <TabsContent value="electricity" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Zap className="w-5 h-5" />
                    Electricity Bills
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Provider Selection */}
                  <div>
                    <Label>Select Distribution Company</Label>
                    <div className="grid grid-cols-3 gap-2 mt-2">
                      {services.electricity.providers.map((provider) => (
                        <Button
                          key={provider}
                          variant={selectedProvider === provider ? "default" : "outline"}
                          onClick={() => setSelectedProvider(provider)}
                          className="h-12 text-xs"
                        >
                          {provider}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Meter Number */}
                  <div>
                    <Label htmlFor="meterNumber">Meter Number</Label>
                    <Input
                      id="meterNumber"
                      value={formData.meterNumber}
                      onChange={(e) => setFormData(prev => ({ ...prev, meterNumber: e.target.value }))}
                      placeholder="Enter meter number"
                    />
                  </div>

                  {/* Quick Amounts */}
                  <div>
                    <Label>Quick Amounts</Label>
                    <div className="grid grid-cols-3 gap-2 mt-2">
                      {services.electricity.quickAmounts.map((amount) => (
                        <Button
                          key={amount}
                          variant="outline"
                          onClick={() => handleQuickAmount(amount)}
                          className="h-12"
                        >
                          {formatNaira(amount)}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Custom Amount */}
                  <div>
                    <Label htmlFor="amount">Amount</Label>
                    <Input
                      id="amount"
                      type="number"
                      value={formData.amount}
                      onChange={(e) => setFormData(prev => ({ ...prev, amount: e.target.value }))}
                      placeholder="Enter amount"
                      min="500"
                      max={spendingBalance}
                    />
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* Cable TV Tab */}
          <TabsContent value="cable" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Tv className="w-5 h-5" />
                    Cable TV Subscription
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Provider Selection */}
                  <div>
                    <Label>Select Provider</Label>
                    <div className="grid grid-cols-3 gap-2 mt-2">
                      {services.cable.providers.map((provider) => (
                        <Button
                          key={provider}
                          variant={selectedProvider === provider ? "default" : "outline"}
                          onClick={() => setSelectedProvider(provider)}
                          className="h-12"
                        >
                          {provider}
                        </Button>
                      ))}
                    </div>
                  </div>

                  {/* Account Number */}
                  <div>
                    <Label htmlFor="accountNumber">Smart Card/Account Number</Label>
                    <Input
                      id="accountNumber"
                      value={formData.accountNumber}
                      onChange={(e) => setFormData(prev => ({ ...prev, accountNumber: e.target.value }))}
                      placeholder="Enter smart card number"
                    />
                  </div>

                  {/* Packages */}
                  {selectedProvider && services.cable.packages[selectedProvider as keyof typeof services.cable.packages] && (
                    <div>
                      <Label>Select Package</Label>
                      <div className="grid gap-2 mt-2">
                        {services.cable.packages[selectedProvider as keyof typeof services.cable.packages].map((pkg, index) => (
                          <Button
                            key={index}
                            variant={formData.package === pkg.name ? "default" : "outline"}
                            onClick={() => handlePackageSelect(pkg)}
                            className="justify-between h-auto p-3"
                          >
                            <span>{pkg.name}</span>
                            <Badge>{formatNaira(pkg.price)}</Badge>
                          </Button>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>
        </Tabs>

        {/* Payment Summary */}
        {formData.amount && selectedProvider && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="mt-6"
          >
            <Card>
              <CardHeader>
                <CardTitle>Payment Summary</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span>Service:</span>
                    <span className="font-medium">{services[activeTab as keyof typeof services]?.title}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Provider:</span>
                    <span className="font-medium">{selectedProvider}</span>
                  </div>
                  {formData.package && (
                    <div className="flex justify-between">
                      <span>Package:</span>
                      <span className="font-medium">{formData.package}</span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span>Amount:</span>
                    <span className="font-bold text-lg">{formatNaira(parseFloat(formData.amount))}</span>
                  </div>
                  <hr />
                  <div className="flex justify-between">
                    <span>Total:</span>
                    <span className="font-bold text-xl text-blue-600">{formatNaira(parseFloat(formData.amount))}</span>
                  </div>
                </div>

                {parseFloat(formData.amount) > spendingBalance && (
                  <Alert className="mt-4">
                    <AlertDescription>
                      Insufficient balance. Please top up your spending wallet.
                    </AlertDescription>
                  </Alert>
                )}

                <Button
                  onClick={handlePayment}
                  disabled={!canProceed() || isProcessing}
                  className="w-full mt-4 bg-blue-600 hover:bg-blue-700"
                  size="lg"
                >
                  {isProcessing ? "Processing Payment..." : "Pay Now"}
                </Button>
              </CardContent>
            </Card>
          </motion.div>
        )}
      </div>
    </div>
  );
}