import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Loader2, Users, Database, AlertTriangle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface AdminToolsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

interface NoDataClient {
  username: string;
  name: string;
  msisdn: string;
}

interface NoDataResponse {
  success: boolean;
  year: number;
  month: number;
  monthName: string;
  clients: NoDataClient[];
  count: number;
}

export default function AdminToolsModal({ isOpen, onClose }: AdminToolsModalProps) {
  const [refreshing, setRefreshing] = useState(false);
  const [loadingNoData, setLoadingNoData] = useState(false);
  const [noDataClients, setNoDataClients] = useState<NoDataResponse | null>(null);
  const { toast } = useToast();

  const handleRefreshAllStats = async () => {
    setRefreshing(true);
    try {
      const response = await fetch('/api/admin/refresh-mtn-stats', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        const result = await response.json();
        toast({
          title: "Refresh Complete",
          description: result.message,
          variant: "default",
        });
      } else {
        throw new Error('Failed to refresh statistics');
      }
    } catch (error) {
      console.error('Refresh error:', error);
      toast({
        title: "Refresh Failed",
        description: "Failed to refresh MTN statistics. Please try again.",
        variant: "destructive",
      });
    }
    setRefreshing(false);
  };

  const handleLoadNoDataClients = async () => {
    setLoadingNoData(true);
    try {
      const response = await fetch('/api/admin/mtn-no-data', {
        method: 'GET',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        const result = await response.json();
        setNoDataClients(result);
      } else {
        throw new Error('Failed to load clients with no data');
      }
    } catch (error) {
      console.error('No data clients error:', error);
      toast({
        title: "Load Failed",
        description: "Failed to load clients with no data usage. Please try again.",
        variant: "destructive",
      });
    }
    setLoadingNoData(false);
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center">
            <Database className="w-5 h-5 mr-2 text-blue-600" />
            MTN Fixed Admin Tools
          </DialogTitle>
        </DialogHeader>
        
        <div className="space-y-6">
          {/* Bulk Refresh Section */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Database className="w-5 h-5 mr-2" />
                Bulk Statistics Refresh
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-gray-600">
                Refresh usage statistics for all MTN Fixed clients for the current month. 
                This will save data to the database for admin reporting purposes and does not affect live client statistics.
              </p>
              <Button
                onClick={handleRefreshAllStats}
                disabled={refreshing}
                className="w-full"
              >
                {refreshing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Refreshing All Statistics...
                  </>
                ) : (
                  <>
                    <Database className="w-4 h-4 mr-2" />
                    Refresh All Stats
                  </>
                )}
              </Button>
            </CardContent>
          </Card>

          {/* No Data Usage Section */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <AlertTriangle className="w-5 h-5 mr-2" />
                Clients with No Data Usage
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-gray-600">
                View MTN Fixed clients who have not used any data in the current month based on cached statistics.
              </p>
              <Button
                onClick={handleLoadNoDataClients}
                disabled={loadingNoData}
                variant="outline"
                className="w-full"
              >
                {loadingNoData ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Loading...
                  </>
                ) : (
                  <>
                    <Users className="w-4 h-4 mr-2" />
                    No Data Used for {new Date().toLocaleString('default', { month: 'long' })}
                  </>
                )}
              </Button>

              {noDataClients && (
                <div className="mt-6 space-y-4">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium text-gray-900">
                      {noDataClients.monthName} {noDataClients.year} - No Data Usage
                    </h4>
                    <Badge variant="secondary">
                      {noDataClients.count} clients
                    </Badge>
                  </div>

                  {noDataClients.count === 0 ? (
                    <div className="text-center py-8">
                      <Users className="w-12 h-12 text-green-400 mx-auto mb-2" />
                      <p className="text-green-600">All MTN Fixed clients have used data this month!</p>
                    </div>
                  ) : (
                    <div className="max-h-96 overflow-y-auto border rounded-lg">
                      <div className="grid gap-2 p-4">
                        {noDataClients.clients.map((client, index) => (
                          <div key={index} className="flex items-center justify-between p-3 bg-red-50 border border-red-200 rounded-lg">
                            <div>
                              <div className="font-medium text-gray-900">{client.name}</div>
                              <div className="text-sm text-gray-600">
                                Username: {client.username}
                              </div>
                              {client.msisdn && (
                                <div className="text-sm text-gray-600">
                                  MSISDN: {client.msisdn}
                                </div>
                              )}
                            </div>
                            <Badge variant="destructive">
                              No Data
                            </Badge>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Info Section */}
          <Card className="border-blue-200 bg-blue-50">
            <CardContent className="p-4">
              <div className="flex items-start space-x-2">
                <Database className="w-5 h-5 text-blue-600 mt-0.5" />
                <div className="text-sm text-blue-800">
                  <p className="font-medium mb-1">Important Notes:</p>
                  <ul className="list-disc list-inside space-y-1">
                    <li>These tools use cached statistics and do not affect live client data</li>
                    <li>Bulk refresh processes all MTN Fixed clients for the current month</li>
                    <li>Results are saved to the database for reporting and analysis</li>
                    <li>Run bulk refresh before checking for clients with no data usage</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </DialogContent>
    </Dialog>
  );
}