import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard';
import { ToggleField } from './components/ToggleField';
import { GenericGatewayForm } from '@/components/settings/GenericGatewayForm';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { CreditCard, Banknote, Settings, RefreshCw, ExternalLink, Loader2, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';

interface GatewayField {
  id: string;
  type: string;
  title: string;
  description: string;
  default: string | boolean;
  value: string | boolean;  // Current saved value
  placeholder?: string;
  required: boolean;
  options?: Record<string, string>;
  custom_attributes?: Record<string, string>;
}

interface PaymentGateway {
  id: string;
  title: string;
  description: string;
  enabled: boolean;
  type: 'manual' | 'provider' | 'other';
  icon: string;
  method_title: string;
  method_description: string;
  supports: string[];
  requirements: {
    met: boolean;
    missing: string[];
  };
  settings: {
    basic: Record<string, GatewayField>;
    api: Record<string, GatewayField>;
    advanced: Record<string, GatewayField>;
  };
  has_fields: boolean;
  webhook_url: string | null;
  has_custom_ui: boolean;
  wc_settings_url: string;
}

export default function PaymentsPage() {
  const queryClient = useQueryClient();
  const [selectedGateway, setSelectedGateway] = useState<PaymentGateway | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [togglingGateway, setTogglingGateway] = useState<string | null>(null);

  // Fetch all payment gateways
  const { data: gateways = [], isLoading, refetch } = useQuery({
    queryKey: ['payment-gateways'],
    queryFn: () => api.get('/payments/gateways'),
    refetchOnWindowFocus: true,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Toggle gateway mutation
  const toggleMutation = useMutation({
    mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) => {
      setTogglingGateway(id);
      return api.post(`/payments/gateways/${id}/toggle`, { enabled });
    },
    onSuccess: async () => {
      // Wait for refetch to complete before showing toast
      await queryClient.invalidateQueries({ queryKey: ['payment-gateways'] });
      toast.success('Gateway updated successfully');
      setTogglingGateway(null);
    },
    onError: () => {
      toast.error('Failed to update gateway');
      setTogglingGateway(null);
    },
  });

  // Save gateway settings mutation
  const saveMutation = useMutation({
    mutationFn: ({ id, settings }: { id: string; settings: Record<string, unknown> }) =>
      api.post(`/payments/gateways/${id}`, settings),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['payment-gateways'] });
      toast.success('Settings saved successfully');
      setIsModalOpen(false);
      setSelectedGateway(null);
    },
    onError: () => {
      toast.error('Failed to save settings');
    },
  });

  const handleToggle = (id: string, enabled: boolean) => {
    toggleMutation.mutate({ id, enabled });
  };

  const handleManageGateway = (gateway: PaymentGateway) => {
    setSelectedGateway(gateway);
    setIsModalOpen(true);
  };

  const handleSaveGateway = async (settings: Record<string, unknown>) => {
    if (!selectedGateway) return;
    await saveMutation.mutateAsync({ id: selectedGateway.id, settings });
  };

  // Categorize gateways
  const manualGateways = gateways.filter((g: PaymentGateway) => g.type === 'manual');
  // Combine provider and other into single "3rd party" category
  const thirdPartyGateways = gateways.filter((g: PaymentGateway) => g.type === 'provider' || g.type === 'other');

  if (isLoading) {
    return (
      <SettingsLayout title="Payments" description="Manage how you get paid">
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      </SettingsLayout>
    );
  }

  return (
    <>
      <SettingsLayout 
        title="Payments" 
        description="Manage how you get paid"
        action={
          <Button
            variant="outline"
            size="sm"
            onClick={() => refetch()}
            disabled={isLoading}
          >
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </Button>
        }
      >

        {/* Manual Payment Methods - First priority */}
        <SettingsCard
          title="Manual Payment Methods"
          description="Accept payments outside your online store"
        >
          {manualGateways.length === 0 ? (
            <p className="text-sm text-muted-foreground">No manual payment methods available</p>
          ) : (
            <div className="space-y-4">
              {manualGateways.map((gateway: PaymentGateway) => (
                <div
                  key={gateway.id}
                  className="border rounded-lg p-4"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-muted rounded-lg">
                        <Banknote className="h-5 w-5 text-muted-foreground" />
                      </div>
                      <div>
                        <h3 className="font-medium">{gateway.method_title || gateway.title}</h3>
                        {gateway.description && (
                          <p className="text-sm text-muted-foreground mt-1">
                            {gateway.description}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {gateway.enabled && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleManageGateway(gateway)}
                        >
                          <Settings className="h-4 w-4" />
                        </Button>
                      )}
                      <ToggleField
                        id={gateway.id}
                        label=""
                        checked={gateway.enabled}
                        onCheckedChange={(checked) => handleToggle(gateway.id, checked)}
                        disabled={togglingGateway === gateway.id}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </SettingsCard>

        {/* Online Payment Methods - Flat list */}
        {thirdPartyGateways.length > 0 && (
          <SettingsCard
            title="Online Payment Methods"
            description="Accept credit cards, digital wallets, and other online payments"
          >
            <div className="space-y-4">
              {thirdPartyGateways.map((gateway: PaymentGateway) => (
                <div
                  key={gateway.id}
                  className="border rounded-lg p-4 hover:border-primary/50 transition-colors"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-4 flex-1">
                      <div className={`p-2 rounded-lg ${gateway.enabled ? 'bg-green-500/20 text-green-500' : 'bg-primary/10 text-primary'}`}>
                        <CreditCard className="h-6 w-6" />
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="font-semibold">
                            {gateway.method_title || gateway.title}
                          </h3>
                        </div>
                        {gateway.method_description && (
                          <p className="text-sm text-muted-foreground mb-2">
                            {gateway.method_description}
                          </p>
                        )}
                        {!gateway.requirements.met && (
                          <Alert variant="destructive" className="mt-2">
                            <AlertTriangle className="h-4 w-4" />
                            <AlertDescription>
                              Requirements not met: {gateway.requirements.missing.join(', ')}
                            </AlertDescription>
                          </Alert>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-0">
                      {gateway.enabled && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleManageGateway(gateway)}
                        >
                          <Settings className="h-4 w-4" />
                        </Button>
                      )}
                      <ToggleField
                        id={gateway.id}
                        label=""
                        checked={gateway.enabled}
                        onCheckedChange={(checked) => handleToggle(gateway.id, checked)}
                        disabled={!gateway.requirements.met || togglingGateway === gateway.id}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </SettingsCard>
        )}
      </SettingsLayout>

      {/* Gateway Settings Modal */}
      {selectedGateway && (
        <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
          <DialogContent className="max-w-2xl max-h-[100vh] flex flex-col p-0 gap-0">
            <DialogHeader className="px-6 pt-6 pb-4 border-b shrink-0">
              <DialogTitle>{selectedGateway.title} Settings</DialogTitle>
            </DialogHeader>
            <div className="flex-1 overflow-y-auto p-6 min-h-0">
              <GenericGatewayForm
                gateway={selectedGateway}
                onSave={handleSaveGateway}
                onCancel={() => setIsModalOpen(false)}
                hideFooter
              />
            </div>
            {/* Footer outside scrollable area */}
            <div className="border-t px-4 sm:px-6 py-3 sm:py-4 flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-0 sm:justify-between shrink-0 bg-background sm:rounded-b-lg">
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsModalOpen(false)}
                disabled={saveMutation.isPending}
                className="order-3 sm:order-1"
              >
                Cancel
              </Button>
              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 order-1 sm:order-2">
                <Button
                  type="button"
                  variant="ghost"
                  asChild
                  className="justify-center"
                >
                  <a
                    href={selectedGateway.wc_settings_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1"
                  >
                    View in WooCommerce
                    <ExternalLink className="h-4 w-4" />
                  </a>
                </Button>
                <Button 
                  onClick={() => {
                    const form = document.querySelector('form');
                    if (form) form.requestSubmit();
                  }}
                  disabled={saveMutation.isPending}
                  className="order-1 sm:order-2"
                >
                  {saveMutation.isPending ? 'Saving...' : 'Save Settings'}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      )}
    </>
  );
}
