import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { 
  CreditCard, 
  Save, 
  Plus, 
  Edit, 
  Trash2, 
  Shield,
  CheckCircle,
  XCircle,
  Settings,
  DollarSign,
  Globe,
  Key
} from "lucide-react";

interface PaymentGateway {
  id: number;
  name: string;
  displayName: string;
  provider: string;
  isActive: boolean;
  isSandbox: boolean;
  config: {
    publicKey?: string;
    secretKey?: string;
    webhookSecret?: string;
    merchantId?: string;
    apiKey?: string;
    baseUrl?: string;
  };
  supportedCurrencies: string[];
  fees: {
    percentage: number;
    fixed: number;
    currency: string;
  };
}

const gatewayProviders = [
  {
    provider: "stripe",
    displayName: "Stripe",
    description: "Popular payment processor with global reach",
    logo: "🟣",
    fields: [
      { key: "publicKey", label: "Publishable Key", type: "text", required: true },
      { key: "secretKey", label: "Secret Key", type: "password", required: true },
      { key: "webhookSecret", label: "Webhook Secret", type: "password", required: false }
    ],
    currencies: ["USD", "EUR", "GBP", "CAD", "AUD", "JPY"]
  },
  {
    provider: "paypal",
    displayName: "PayPal",
    description: "Trusted payment solution worldwide",
    logo: "🔵",
    fields: [
      { key: "clientId", label: "Client ID", type: "text", required: true },
      { key: "clientSecret", label: "Client Secret", type: "password", required: true }
    ],
    currencies: ["USD", "EUR", "GBP", "CAD", "AUD"]
  },
  {
    provider: "flutterwave",
    displayName: "Flutterwave",
    description: "African payment gateway",
    logo: "🟡",
    fields: [
      { key: "publicKey", label: "Public Key", type: "text", required: true },
      { key: "secretKey", label: "Secret Key", type: "password", required: true }
    ],
    currencies: ["NGN", "KES", "GHS", "UGX", "ZAR", "USD"]
  },
  {
    provider: "paystack",
    displayName: "Paystack",
    description: "Nigerian payment processor",
    logo: "🔷",
    fields: [
      { key: "publicKey", label: "Public Key", type: "text", required: true },
      { key: "secretKey", label: "Secret Key", type: "password", required: true }
    ],
    currencies: ["NGN", "GHS", "ZAR", "KES"]
  },
  {
    provider: "paytm",
    displayName: "Paytm",
    description: "Indian digital payment platform",
    logo: "🟦",
    fields: [
      { key: "merchantId", label: "Merchant ID", type: "text", required: true },
      { key: "merchantKey", label: "Merchant Key", type: "password", required: true }
    ],
    currencies: ["INR"]
  },
  {
    provider: "coingate",
    displayName: "CoinGate",
    description: "Cryptocurrency payment processor",
    logo: "🪙",
    fields: [
      { key: "apiKey", label: "API Key", type: "password", required: true },
      { key: "apiSecret", label: "API Secret", type: "password", required: true }
    ],
    currencies: ["BTC", "ETH", "LTC", "USD", "EUR"]
  },
  {
    provider: "sspay",
    displayName: "SSPay",
    description: "Secure payment gateway",
    logo: "🔒",
    fields: [
      { key: "merchantId", label: "Merchant ID", type: "text", required: true },
      { key: "apiKey", label: "API Key", type: "password", required: true }
    ],
    currencies: ["USD", "EUR"]
  },
  {
    provider: "payumoney",
    displayName: "PayUMoney",
    description: "Indian payment gateway",
    logo: "🟢",
    fields: [
      { key: "merchantKey", label: "Merchant Key", type: "text", required: true },
      { key: "salt", label: "Salt", type: "password", required: true }
    ],
    currencies: ["INR"]
  },
  {
    provider: "razorpay",
    displayName: "Razorpay",
    description: "Complete payment solution for India",
    logo: "🔵",
    fields: [
      { key: "keyId", label: "Key ID", type: "text", required: true },
      { key: "keySecret", label: "Key Secret", type: "password", required: true }
    ],
    currencies: ["INR", "USD", "EUR", "GBP"]
  }
];

export default function PaymentGateways() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedGateway, setSelectedGateway] = useState<PaymentGateway | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [selectedProvider, setSelectedProvider] = useState("");

  // Fetch payment gateways
  const { data: gateways = [], isLoading } = useQuery({
    queryKey: ["/api/payment-gateways"],
    queryFn: async () => {
      const response = await fetch("/api/payment-gateways");
      if (!response.ok) throw new Error("Failed to fetch payment gateways");
      return response.json();
    }
  });

  // Create gateway mutation
  const createGatewayMutation = useMutation({
    mutationFn: async (gateway: Partial<PaymentGateway>) => {
      const response = await fetch("/api/payment-gateways", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(gateway)
      });
      if (!response.ok) throw new Error("Failed to create payment gateway");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/payment-gateways"] });
      toast({ title: "Payment gateway created successfully" });
      setIsEditing(false);
      setSelectedGateway(null);
    }
  });

  // Update gateway mutation
  const updateGatewayMutation = useMutation({
    mutationFn: async ({ id, ...gateway }: Partial<PaymentGateway> & { id: number }) => {
      const response = await fetch(`/api/payment-gateways/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(gateway)
      });
      if (!response.ok) throw new Error("Failed to update payment gateway");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/payment-gateways"] });
      toast({ title: "Payment gateway updated successfully" });
      setIsEditing(false);
    }
  });

  // Test connection mutation
  const testConnectionMutation = useMutation({
    mutationFn: async (gatewayId: number) => {
      const response = await fetch(`/api/payment-gateways/${gatewayId}/test`, {
        method: "POST"
      });
      if (!response.ok) throw new Error("Connection test failed");
      return response.json();
    },
    onSuccess: () => {
      toast({ title: "Connection test successful", variant: "default" });
    },
    onError: () => {
      toast({ title: "Connection test failed", variant: "destructive" });
    }
  });

  const handleCreateGateway = (provider: string) => {
    const providerInfo = gatewayProviders.find(p => p.provider === provider);
    if (!providerInfo) return;

    setSelectedGateway({
      id: 0,
      name: provider,
      displayName: providerInfo.displayName,
      provider: provider,
      isActive: false,
      isSandbox: true,
      config: {},
      supportedCurrencies: providerInfo.currencies,
      fees: {
        percentage: 2.9,
        fixed: 0.30,
        currency: "USD"
      }
    });
    setSelectedProvider(provider);
    setIsEditing(true);
  };

  const handleSaveGateway = () => {
    if (!selectedGateway) return;
    
    if (selectedGateway.id === 0) {
      createGatewayMutation.mutate(selectedGateway);
    } else {
      updateGatewayMutation.mutate(selectedGateway);
    }
  };

  const getProviderInfo = (provider: string) => {
    return gatewayProviders.find(p => p.provider === provider);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Payment Gateways</h1>
          <p className="text-muted-foreground">
            Configure payment processors for your forms and applications
          </p>
        </div>
        <Badge variant="secondary" className="flex items-center space-x-1">
          <Shield className="h-3 w-3" />
          <span>9 Providers</span>
        </Badge>
      </div>

      <Tabs defaultValue="configured" className="w-full">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="configured">Configured Gateways</TabsTrigger>
          <TabsTrigger value="available">Available Providers</TabsTrigger>
        </TabsList>

        <TabsContent value="configured" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Gateway List */}
            <Card>
              <CardHeader>
                <CardTitle>Active Payment Gateways</CardTitle>
                <CardDescription>Manage your configured payment processors</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {isLoading ? (
                  <div className="text-center py-4">Loading gateways...</div>
                ) : gateways.length === 0 ? (
                  <div className="text-center py-4 text-muted-foreground">
                    No payment gateways configured yet
                  </div>
                ) : (
                  gateways.map((gateway: PaymentGateway) => (
                    <div
                      key={gateway.id}
                      className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                        selectedGateway?.id === gateway.id
                          ? "border-primary bg-primary/5"
                          : "border-gray-200 hover:border-gray-300"
                      }`}
                      onClick={() => {
                        setSelectedGateway(gateway);
                        setSelectedProvider(gateway.provider);
                        setIsEditing(false);
                      }}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-1">
                            <span className="text-lg">{getProviderInfo(gateway.provider)?.logo}</span>
                            <h3 className="font-medium">{gateway.displayName}</h3>
                            {gateway.isActive ? (
                              <Badge variant="default" className="text-xs">
                                <CheckCircle className="h-3 w-3 mr-1" />
                                Active
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">
                                <XCircle className="h-3 w-3 mr-1" />
                                Inactive
                              </Badge>
                            )}
                            {gateway.isSandbox && (
                              <Badge variant="outline" className="text-xs">Sandbox</Badge>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">
                            Supports: {gateway.supportedCurrencies.slice(0, 3).join(", ")}
                            {gateway.supportedCurrencies.length > 3 && ` +${gateway.supportedCurrencies.length - 3} more`}
                          </p>
                          <p className="text-xs text-muted-foreground mt-1">
                            Fees: {gateway.fees.percentage}% + {gateway.fees.currency} {gateway.fees.fixed}
                          </p>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={(e) => {
                              e.stopPropagation();
                              testConnectionMutation.mutate(gateway.id);
                            }}
                            disabled={testConnectionMutation.isPending}
                          >
                            <Shield className="h-3 w-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedGateway(gateway);
                              setSelectedProvider(gateway.provider);
                              setIsEditing(true);
                            }}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </CardContent>
            </Card>

            {/* Gateway Configuration */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Settings className="h-5 w-5" />
                  <span>{isEditing ? 'Configure Gateway' : 'Gateway Details'}</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {!selectedGateway ? (
                  <div className="text-center py-8 text-muted-foreground">
                    Select a gateway to view details or configure a new one
                  </div>
                ) : (
                  <div className="space-y-4">
                    {isEditing ? (
                      <>
                        <div>
                          <Label>Display Name</Label>
                          <Input
                            value={selectedGateway.displayName}
                            onChange={(e) => setSelectedGateway(prev => prev ? {...prev, displayName: e.target.value} : null)}
                          />
                        </div>

                        {/* Dynamic fields based on provider */}
                        {getProviderInfo(selectedProvider)?.fields.map((field) => (
                          <div key={field.key}>
                            <Label>{field.label} {field.required && <span className="text-red-500">*</span>}</Label>
                            <Input
                              type={field.type}
                              value={selectedGateway.config[field.key] || ""}
                              onChange={(e) => setSelectedGateway(prev => prev ? {
                                ...prev,
                                config: { ...prev.config, [field.key]: e.target.value }
                              } : null)}
                              placeholder={`Enter ${field.label.toLowerCase()}`}
                            />
                          </div>
                        ))}

                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <Label>Fee Percentage</Label>
                            <Input
                              type="number"
                              step="0.1"
                              value={selectedGateway.fees.percentage}
                              onChange={(e) => setSelectedGateway(prev => prev ? {
                                ...prev,
                                fees: { ...prev.fees, percentage: parseFloat(e.target.value) || 0 }
                              } : null)}
                            />
                          </div>
                          <div>
                            <Label>Fixed Fee</Label>
                            <Input
                              type="number"
                              step="0.01"
                              value={selectedGateway.fees.fixed}
                              onChange={(e) => setSelectedGateway(prev => prev ? {
                                ...prev,
                                fees: { ...prev.fees, fixed: parseFloat(e.target.value) || 0 }
                              } : null)}
                            />
                          </div>
                          <div>
                            <Label>Currency</Label>
                            <Select
                              value={selectedGateway.fees.currency}
                              onValueChange={(value) => setSelectedGateway(prev => prev ? {
                                ...prev,
                                fees: { ...prev.fees, currency: value }
                              } : null)}
                            >
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {selectedGateway.supportedCurrencies.map((currency) => (
                                  <SelectItem key={currency} value={currency}>
                                    {currency}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>

                        <div className="flex items-center space-x-4">
                          <div className="flex items-center space-x-2">
                            <Switch
                              checked={selectedGateway.isSandbox}
                              onCheckedChange={(checked) => setSelectedGateway(prev => prev ? {...prev, isSandbox: checked} : null)}
                            />
                            <Label>Sandbox Mode</Label>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Switch
                              checked={selectedGateway.isActive}
                              onCheckedChange={(checked) => setSelectedGateway(prev => prev ? {...prev, isActive: checked} : null)}
                            />
                            <Label>Active</Label>
                          </div>
                        </div>

                        <div className="flex items-center space-x-2 pt-4">
                          <Button onClick={handleSaveGateway} className="flex items-center space-x-2">
                            <Save className="h-4 w-4" />
                            <span>Save Configuration</span>
                          </Button>
                          <Button 
                            variant="outline" 
                            onClick={() => setIsEditing(false)}
                          >
                            Cancel
                          </Button>
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="space-y-3">
                          <div className="flex items-center space-x-2">
                            <span className="text-2xl">{getProviderInfo(selectedGateway.provider)?.logo}</span>
                            <div>
                              <h3 className="font-medium">{selectedGateway.displayName}</h3>
                              <p className="text-sm text-muted-foreground">
                                {getProviderInfo(selectedGateway.provider)?.description}
                              </p>
                            </div>
                          </div>
                          
                          <div className="grid grid-cols-2 gap-4 text-sm">
                            <div>
                              <span className="font-medium">Status:</span>
                              <Badge variant={selectedGateway.isActive ? "default" : "secondary"} className="ml-2">
                                {selectedGateway.isActive ? "Active" : "Inactive"}
                              </Badge>
                            </div>
                            <div>
                              <span className="font-medium">Mode:</span>
                              <Badge variant={selectedGateway.isSandbox ? "outline" : "default"} className="ml-2">
                                {selectedGateway.isSandbox ? "Sandbox" : "Live"}
                              </Badge>
                            </div>
                            <div>
                              <span className="font-medium">Fees:</span>
                              <span className="ml-2">{selectedGateway.fees.percentage}% + {selectedGateway.fees.currency} {selectedGateway.fees.fixed}</span>
                            </div>
                            <div>
                              <span className="font-medium">Currencies:</span>
                              <span className="ml-2">{selectedGateway.supportedCurrencies.length}</span>
                            </div>
                          </div>
                        </div>

                        <div className="flex items-center space-x-2 pt-4">
                          <Button 
                            onClick={() => setIsEditing(true)}
                            className="flex items-center space-x-2"
                          >
                            <Edit className="h-4 w-4" />
                            <span>Configure</span>
                          </Button>
                          <Button 
                            variant="outline"
                            onClick={() => testConnectionMutation.mutate(selectedGateway.id)}
                            disabled={testConnectionMutation.isPending}
                            className="flex items-center space-x-2"
                          >
                            <Shield className="h-4 w-4" />
                            <span>Test Connection</span>
                          </Button>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="available" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Available Payment Providers</CardTitle>
              <CardDescription>
                Choose from our supported payment gateways to start accepting payments
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {gatewayProviders.map((provider) => (
                  <div key={provider.provider} className="border rounded-lg p-4 hover:border-primary transition-colors">
                    <div className="space-y-3">
                      <div className="flex items-center space-x-3">
                        <span className="text-2xl">{provider.logo}</span>
                        <div>
                          <h3 className="font-medium">{provider.displayName}</h3>
                          <p className="text-sm text-muted-foreground">{provider.description}</p>
                        </div>
                      </div>
                      
                      <div className="space-y-2">
                        <div className="text-xs text-muted-foreground">
                          <span className="font-medium">Supported Currencies:</span>
                          <div className="flex flex-wrap gap-1 mt-1">
                            {provider.currencies.slice(0, 4).map((currency) => (
                              <Badge key={currency} variant="outline" className="text-xs">
                                {currency}
                              </Badge>
                            ))}
                            {provider.currencies.length > 4 && (
                              <Badge variant="outline" className="text-xs">
                                +{provider.currencies.length - 4}
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>

                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="w-full"
                        onClick={() => handleCreateGateway(provider.provider)}
                      >
                        <Plus className="h-3 w-3 mr-2" />
                        Configure
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}