import React, { useState, useEffect } from "react";
import { apiClient } from "@/utils/apiClient";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Loader2, AlertCircle, CheckCircle, RefreshCw } from "lucide-react";

const AcotTest = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);
  const [connectionStatus, setConnectionStatus] = useState(null);

  const testConnection = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.get("/api/acot/test/test-connection");
      setConnectionStatus(response.data);
    } catch (err) {
      setError(err.response?.data?.error || err.message);
      setConnectionStatus(null);
    } finally {
      setLoading(false);
    }
  };

  const fetchOrderCount = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.get("/api/acot/test/order-count");
      setData(response.data.data);
    } catch (err) {
      setError(err.response?.data?.error || err.message);
      setData(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    testConnection();
  }, []);

  return (
    <Card className="w-full max-w-md">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          ACOT Server Test
          <Button
            size="icon"
            variant="outline"
            onClick={() => {
              testConnection();
              if (connectionStatus?.success) {
                fetchOrderCount();
              }
            }}
            disabled={loading}
          >
            {loading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <RefreshCw className="h-4 w-4" />
            )}
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Connection Status */}
        <div className="space-y-2">
          <h3 className="text-sm font-medium">Connection Status</h3>
          {connectionStatus?.success ? (
            <Alert className="bg-green-50 border-green-200">
              <CheckCircle className="h-4 w-4 text-green-600" />
              <AlertTitle className="text-green-800">Connected</AlertTitle>
              <AlertDescription className="text-green-700">
                {connectionStatus.message}
              </AlertDescription>
            </Alert>
          ) : error ? (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Connection Failed</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          ) : (
            <div className="text-sm text-muted-foreground">
              Testing connection...
            </div>
          )}
        </div>

        {/* Order Count */}
        {connectionStatus?.success && (
          <div className="space-y-2">
            <Button
              onClick={fetchOrderCount}
              disabled={loading}
              className="w-full"
            >
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Loading...
                </>
              ) : (
                "Fetch Order Count"
              )}
            </Button>

            {data && (
              <div className="p-4 bg-muted rounded-lg">
                <div className="text-sm text-muted-foreground">
                  Total Orders in Database
                </div>
                <div className="text-2xl font-bold">
                  {data.orderCount?.toLocaleString()}
                </div>
                <div className="text-xs text-muted-foreground mt-1">
                  Last updated: {new Date(data.timestamp).toLocaleTimeString()}
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default AcotTest; 