import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { Loader2, Activity, Clock, TrendingUp, Calendar, User, MapPin, Wifi, Shield, Zap, Unlock } from "lucide-react";
import type { Client } from "@shared/schema";

interface UsageStatsModalProps {
  client: Client | null;
  isOpen: boolean;
  onClose: () => void;
}

interface MonthlyUsage {
  year: number;
  month: number;
  monthName: string;
  usage: number; // in GB
  connectedTime: number; // in hours
  error?: string;
}

interface AccountInfo {
  username?: string;
  msisdn?: string;
  accountStatus?: string;
  serviceStatus?: string;
  package?: string;
  ipAddress?: string;
  macAddress?: string;
  lastLogin?: string;
  creationDate?: string;
  expiryDate?: string;
  location?: string;
  error?: string;
}

interface ActiveSession {
  connect_time?: string;
  session_id?: string;
  subscriber_ip?: string;
  UserName?: string;
  MSISDSN?: string;
}

export default function UsageStatsModal({ client, isOpen, onClose }: UsageStatsModalProps) {
  const [usageData, setUsageData] = useState<MonthlyUsage[]>([]);
  const [accountInfo, setAccountInfo] = useState<AccountInfo | null>(null);
  const [activeSessions, setActiveSessions] = useState<ActiveSession[]>([]);
  const [loading, setLoading] = useState(false);
  const [accountLoading, setAccountLoading] = useState(false);
  const [sessionsLoading, setSessionsLoading] = useState(false);
  const [unlocking, setUnlocking] = useState(false);
  const [showUnlockForm, setShowUnlockForm] = useState(false);
  const [unlockType, setUnlockType] = useState<"LocationUnlock" | "DeviceUnlock">("LocationUnlock");
  const [unlockComment, setUnlockComment] = useState("");
  const [latitude, setLatitude] = useState("");
  const [longitude, setLongitude] = useState("");
  const { toast } = useToast();

  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;

  // Get last 3 months
  const getLastThreeMonths = () => {
    const months = [];
    for (let i = 2; i >= 0; i--) {
      const date = new Date(currentYear, currentMonth - 1 - i, 1);
      months.push({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        monthName: date.toLocaleString('default', { month: 'long' })
      });
    }
    return months;
  };

  const fetchUsageData = async () => {
    if (!client?.accountNumber) return;

    setLoading(true);
    const months = getLastThreeMonths();
    const results: MonthlyUsage[] = [];

    for (const monthInfo of months) {
      try {
        const monthStr = monthInfo.month.toString().padStart(2, '0');
        const response = await fetch(
          `/api/usage-stats/${encodeURIComponent(client.accountNumber)}?year=${monthInfo.year}&month=${monthStr}`,
          {
            method: 'GET',
            credentials: 'include',
            headers: {
              'Content-Type': 'application/json',
            },
          }
        );
        
        if (response.ok) {
          const apiResponse = await response.json();
          console.log('API Response:', apiResponse); // Debug log
          
          // Handle the API response format: {"ok":true,"data":[{user data}]}
          let usageInBytes = 0;
          let connectedTimeSeconds = 0;
          
          if (apiResponse.ok && apiResponse.data && Array.isArray(apiResponse.data) && apiResponse.data.length > 0) {
            const userData = apiResponse.data[0]; // Get first user's data
            usageInBytes = parseInt(userData.Total || "0", 10);
            
            // Parse ConnectedTime from format "739:03:54" to seconds
            const timeStr = userData.ConnectedTime || "0:00:00";
            const timeParts = timeStr.split(":");
            if (timeParts.length === 3) {
              const hours = parseInt(timeParts[0], 10) || 0;
              const minutes = parseInt(timeParts[1], 10) || 0;
              const seconds = parseInt(timeParts[2], 10) || 0;
              connectedTimeSeconds = (hours * 3600) + (minutes * 60) + seconds;
            }
          }
          
          const usageInGB = Number((usageInBytes / (1024 * 1024 * 1024)).toFixed(2));
          const connectedTimeHours = Math.round(connectedTimeSeconds / 3600); // Convert seconds to hours

          results.push({
            year: monthInfo.year,
            month: monthInfo.month,
            monthName: monthInfo.monthName,
            usage: usageInGB,
            connectedTime: connectedTimeHours
          });
        } else {
          results.push({
            year: monthInfo.year,
            month: monthInfo.month,
            monthName: monthInfo.monthName,
            usage: 0,
            connectedTime: 0,
            error: 'No data available'
          });
        }
      } catch (error) {
        results.push({
          year: monthInfo.year,
          month: monthInfo.month,
          monthName: monthInfo.monthName,
          usage: 0,
          connectedTime: 0,
          error: 'Failed to fetch data'
        });
      }
    }

    setUsageData(results);
    setLoading(false);
  };

  const fetchAccountInfo = async () => {
    if (!client?.accountNumber) return;

    setAccountLoading(true);
    try {
      const response = await fetch(
        `/api/account-info/${encodeURIComponent(client.accountNumber)}`,
        {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (response.ok) {
        const apiResponse = await response.json();
        console.log('Account Info Response:', apiResponse);

        if (apiResponse.ok && apiResponse.data && typeof apiResponse.data === 'object') {
          // API returns data as {"username": {...}} format
          const usernameKey = client.accountNumber;
          const accountData = apiResponse.data[usernameKey];
          
          if (accountData) {
            // Parse coordinates if available
            const latitude = accountData.Latitude || accountData.latitude;
            const longitude = accountData.Longitude || accountData.longitude;
            let location = 'N/A';
            if (latitude && longitude) {
              location = `${latitude}, ${longitude}`;
            }

            setAccountInfo({
              username: usernameKey,
              msisdn: accountData.MSISDN || accountData.msisdn || 'N/A',
              accountStatus: accountData.Status || accountData.status || 'N/A',
              serviceStatus: accountData.Class || accountData.class || 'N/A',
              package: accountData.Package || accountData.package || accountData.Class || 'N/A',
              ipAddress: accountData.IPAddress || accountData.ipAddress || 'N/A',
              macAddress: accountData.MACAddress || accountData.macAddress || 'N/A',
              lastLogin: accountData.LastLogin || accountData.lastLogin || 'N/A',
              creationDate: accountData.CreationDate || accountData.creationDate || 'N/A',
              expiryDate: accountData.ExpiryDate || accountData.expiryDate || 'N/A',
              location: location,
            });
          } else {
            setAccountInfo({ error: 'Account not found in response data' });
          }
        } else {
          setAccountInfo({ error: 'No account data available' });
        }
      } else {
        setAccountInfo({ error: 'Failed to fetch account information' });
      }
    } catch (error) {
      console.error('Account info fetch error:', error);
      setAccountInfo({ error: 'Network error occurred' });
    }
    setAccountLoading(false);
  };

  const fetchCurrentSessions = async () => {
    if (!client?.accountNumber) return;

    setSessionsLoading(true);
    try {
      const response = await fetch(
        `/api/current-sessions/${encodeURIComponent(client.accountNumber)}`,
        {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (response.ok) {
        const apiResponse = await response.json();
        console.log('Current Sessions Response:', apiResponse);

        if (apiResponse.ok && apiResponse.data && Array.isArray(apiResponse.data)) {
          console.log('Setting active sessions:', apiResponse.data);
          setActiveSessions(apiResponse.data);
        } else {
          console.log('No valid session data found');
          setActiveSessions([]);
        }
      } else {
        console.log('Response not ok:', response.status);
        setActiveSessions([]);
      }
    } catch (error) {
      console.error('Current sessions fetch error:', error);
      setActiveSessions([]);
    }
    setSessionsLoading(false);
  };



  const handleUnlockDevice = () => {
    setShowUnlockForm(true);
    setUnlockComment(""); // Reset comment
  };

  const handleSubmitUnlock = async () => {
    if (!client?.accountNumber || !unlockComment.trim()) {
      console.error('[UNLOCK-CLIENT] Missing required data:', {
        hasClient: !!client,
        hasAccountNumber: !!client?.accountNumber,
        hasComment: !!unlockComment.trim()
      });
      
      toast({
        title: "Missing Information",
        description: "Please provide a comment for the unlock request.",
        variant: "destructive",
      });
      return;
    }

    // Validate latitude and longitude for LocationUnlock
    if (unlockType === "LocationUnlock" && (!latitude.trim() || !longitude.trim())) {
      toast({
        title: "Missing Location Data",
        description: "Please enter both latitude and longitude for location unlock.",
        variant: "destructive",
      });
      return;
    }

    console.log('[UNLOCK-CLIENT] Starting unlock process for:', client.accountNumber);
    console.log('[UNLOCK-CLIENT] Unlock type:', unlockType);
    console.log('[UNLOCK-CLIENT] Comment:', unlockComment);

    setUnlocking(true);
    try {
      let requestBody: any = {
        Type: unlockType,
        Username: client.accountNumber,
        Comment: unlockComment.trim()
      };

      // Add location data for LocationUnlock type
      if (unlockType === "LocationUnlock" && latitude.trim() && longitude.trim()) {
        requestBody.Latitude = latitude.trim();
        requestBody.Longitude = longitude.trim();
        console.log('[UNLOCK-CLIENT] Added user-entered coordinates:', { 
          latitude: latitude.trim(), 
          longitude: longitude.trim() 
        });
      }

      console.log('[UNLOCK-CLIENT] Prepared request body:', requestBody);

      const response = await fetch('/api/unlock-device', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
      });

      console.log('[UNLOCK-CLIENT] Backend response status:', response.status);

      if (response.ok) {
        const result = await response.json();
        console.log('[UNLOCK-CLIENT] Backend success response:', result);
        
        toast({
          title: "Unlock Request Successful",
          description: `${unlockType} request has been processed for ${client.name}`,
          variant: "default",
        });
        
        setShowUnlockForm(false);
        setUnlockComment("");
        setLatitude("");
        setLongitude("");
      } else {
        const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
        console.error('[UNLOCK-CLIENT] Backend error response:', errorData);
        
        throw new Error(errorData.message || `Unlock failed with status: ${response.status}`);
      }
    } catch (error) {
      console.error('[UNLOCK-CLIENT] Critical error during unlock:', {
        error: error.message,
        stack: error.stack,
        name: error.name,
        client: client?.accountNumber,
        unlockType,
        timestamp: new Date().toISOString()
      });
      
      toast({
        title: "Unlock Failed",
        description: error.message || "Failed to process unlock request. Please try again.",
        variant: "destructive",
      });
    } finally {
      console.log('[UNLOCK-CLIENT] Unlock process completed, resetting loading state');
      setUnlocking(false);
    }
  };

  useEffect(() => {
    if (isOpen && client) {
      fetchUsageData();
      fetchAccountInfo();
      fetchCurrentSessions();
    }
  }, [isOpen, client]);

  const totalUsage = usageData.reduce((sum, month) => sum + month.usage, 0);
  const averageUsage = usageData.length > 0 ? (totalUsage / usageData.length) : 0;

  return (
    <>
      <Dialog open={isOpen} onOpenChange={onClose}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center space-x-2">
              <Activity className="w-5 h-5 text-blue-600" />
              <span>Usage Statistics - {client?.name}</span>
            </DialogTitle>
          </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
            <span className="ml-2 text-gray-600">Loading usage data...</span>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Client Info */}
            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 border border-blue-200">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-gray-900">{client?.name}</h3>
                  <p className="text-sm text-gray-600">Account: {client?.accountNumber}</p>
                  <p className="text-sm text-gray-600">MSISDN: {client?.msisdn}</p>
                </div>
                <div className="flex flex-col items-end space-y-2">
                  <Badge className="bg-blue-600 text-white">MTN Fixed</Badge>
                  <Button
                    onClick={handleUnlockDevice}
                    disabled={unlocking || !accountInfo}
                    size="sm"
                    className="bg-orange-600 hover:bg-orange-700 text-white"
                  >
                    {unlocking ? (
                      <>
                        <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                        Unlocking...
                      </>
                    ) : (
                      <>
                        <Unlock className="w-4 h-4 mr-2" />
                        Unlock Device/Location
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </div>

            {/* Summary Stats */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                    <TrendingUp className="w-4 h-4 mr-1" />
                    Total Usage (3 Months)
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-blue-600">{totalUsage.toFixed(2)} GB</div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                    <Activity className="w-4 h-4 mr-1" />
                    Average Monthly
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-green-600">{averageUsage.toFixed(2)} GB</div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                    <Calendar className="w-4 h-4 mr-1" />
                    Data Period
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-sm font-semibold text-gray-800">Last 3 Months</div>
                  <div className="text-xs text-gray-600">{usageData[0]?.monthName} - {usageData[2]?.monthName}</div>
                </CardContent>
              </Card>
            </div>

            {/* Monthly Breakdown */}
            <div>
              <h4 className="text-lg font-semibold text-gray-900 mb-4">Monthly Usage Breakdown</h4>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {usageData.map((monthData, index) => (
                  <Card key={index} className="relative overflow-hidden">
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-gray-600 flex items-center justify-between">
                        <span className="flex items-center">
                          <Calendar className="w-4 h-4 mr-1" />
                          {monthData.monthName} {monthData.year}
                        </span>
                        {monthData.error && (
                          <Badge variant="destructive" className="text-xs">Error</Badge>
                        )}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {monthData.error ? (
                        <div className="text-center py-4">
                          <p className="text-sm text-red-600">{monthData.error}</p>
                        </div>
                      ) : (
                        <>
                          <div>
                            <div className="flex items-center justify-between mb-1">
                              <span className="text-sm text-gray-600">Data Usage</span>
                              <span className="text-sm font-medium">{monthData.usage.toFixed(2)} GB</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-2">
                              <div 
                                className="bg-blue-600 h-2 rounded-full" 
                                style={{ width: `${Math.min((monthData.usage / Math.max(...usageData.map(d => d.usage))) * 100, 100)}%` }}
                              ></div>
                            </div>
                          </div>
                          
                          <div className="flex items-center justify-between">
                            <span className="text-sm text-gray-600 flex items-center">
                              <Clock className="w-3 h-3 mr-1" />
                              Connected Time
                            </span>
                            <span className="text-sm font-medium">{monthData.connectedTime}h</span>
                          </div>
                        </>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>

            {/* Account Map Section */}
            <div className="border-t pt-6">
              <h4 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                <User className="w-5 h-5 mr-2 text-blue-600" />
                Account Map
              </h4>
              
              {accountLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-6 h-6 animate-spin text-blue-600 mr-2" />
                  <span className="text-gray-600">Loading account information...</span>
                </div>
              ) : accountInfo?.error ? (
                <Card className="border-red-200 bg-red-50">
                  <CardContent className="p-4">
                    <p className="text-red-600 text-center">{accountInfo.error}</p>
                  </CardContent>
                </Card>
              ) : accountInfo ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {/* Account Details */}
                  <Card>
                    <CardHeader className="pb-3">
                      <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                        <User className="w-4 h-4 mr-1" />
                        Account Details
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div>
                        <span className="text-xs text-gray-500">Username</span>
                        <div className="font-medium text-gray-900">{accountInfo.username || 'N/A'}</div>
                      </div>
                      <div>
                        <span className="text-xs text-gray-500">MSISDN</span>
                        <div className="font-mono text-gray-900">{accountInfo.msisdn || 'N/A'}</div>
                      </div>
                      <div>
                        <span className="text-xs text-gray-500">Package</span>
                        <div className="font-medium text-gray-900">{accountInfo.package || 'N/A'}</div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Status Information */}
                  <Card>
                    <CardHeader className="pb-3">
                      <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                        <Shield className="w-4 h-4 mr-1" />
                        Status Information
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div>
                        <span className="text-xs text-gray-500">Account Status</span>
                        <div>
                          <Badge className={`${accountInfo.accountStatus?.toLowerCase() === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                            {accountInfo.accountStatus || 'Unknown'}
                          </Badge>
                        </div>
                      </div>
                      <div>
                        <span className="text-xs text-gray-500">Service Status</span>
                        <div>
                          <Badge className={`${accountInfo.serviceStatus?.toLowerCase() === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                            {accountInfo.serviceStatus || 'Unknown'}
                          </Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Network Information */}
                  <Card>
                    <CardHeader className="pb-3">
                      <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                        <Wifi className="w-4 h-4 mr-1" />
                        Network Information
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div>
                        <span className="text-xs text-gray-500">IP Address</span>
                        <div className="font-mono text-gray-900">{accountInfo.ipAddress || 'N/A'}</div>
                      </div>
                      <div>
                        <span className="text-xs text-gray-500">MAC Address</span>
                        <div className="font-mono text-gray-900 text-xs">{accountInfo.macAddress || 'N/A'}</div>
                      </div>
                      <div>
                        <span className="text-xs text-gray-500">Location</span>
                        <div className="text-gray-900">{accountInfo.location || 'N/A'}</div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Current Active Sessions */}
                  <Card className="md:col-span-2 lg:col-span-3">
                    <CardHeader className="pb-3">
                      <CardTitle className="text-sm font-medium text-gray-600 flex items-center">
                        <Zap className="w-4 h-4 mr-1" />
                        Current Active Sessions
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      {sessionsLoading ? (
                        <div className="flex items-center justify-center py-4">
                          <Loader2 className="w-4 h-4 animate-spin text-blue-600 mr-2" />
                          <span className="text-gray-600">Loading active sessions...</span>
                        </div>
                      ) : activeSessions.length > 0 ? (
                        <div className="space-y-3">
                          {activeSessions.map((session, index) => (
                            <div key={index} className="p-3 bg-green-50 border border-green-200 rounded-lg">
                              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                                <div>
                                  <span className="text-xs text-green-600 font-medium">Connect Time</span>
                                  <div className="text-sm text-gray-900">{session.connect_time || 'N/A'}</div>
                                </div>
                                <div>
                                  <span className="text-xs text-green-600 font-medium">Session ID</span>
                                  <div className="text-sm font-mono text-gray-900">{session.session_id || 'N/A'}</div>
                                </div>
                                <div>
                                  <span className="text-xs text-green-600 font-medium">IP Address</span>
                                  <div className="text-sm font-mono text-gray-900">{session.subscriber_ip || 'N/A'}</div>
                                </div>
                                <div>
                                  <span className="text-xs text-green-600 font-medium">MSISDN</span>
                                  <div className="text-sm font-mono text-gray-900">{session.MSISDSN || 'N/A'}</div>
                                </div>
                              </div>
                              <div className="mt-2 flex items-center">
                                <Badge className="bg-green-100 text-green-800">
                                  <Activity className="w-3 h-3 mr-1" />
                                  Active Session
                                </Badge>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <div className="text-center py-8">
                          <Zap className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                          <p className="text-gray-500">No active sessions found</p>
                          <p className="text-xs text-gray-400 mt-1">This user is currently offline</p>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                </div>
              ) : (
                <Card className="border-gray-200">
                  <CardContent className="p-8 text-center">
                    <User className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-gray-500">No account information available</p>
                  </CardContent>
                </Card>
              )}
            </div>

            {/* Additional Tools Section */}
            <div className="border-t pt-6">
              <h4 className="text-lg font-semibold text-gray-900 mb-4">Additional Tools</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Card className="border-dashed border-2 border-gray-300">
                  <CardContent className="flex items-center justify-center py-8">
                    <div className="text-center">
                      <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center mx-auto mb-2">
                        <TrendingUp className="w-6 h-6 text-gray-400" />
                      </div>
                      <p className="text-sm text-gray-500">More analytics tools</p>
                    </div>
                  </CardContent>
                </Card>
                
                <Card className="border-dashed border-2 border-gray-300">
                  <CardContent className="flex items-center justify-center py-8">
                    <div className="text-center">
                      <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center mx-auto mb-2">
                        <MapPin className="w-6 h-6 text-gray-400" />
                      </div>
                      <p className="text-sm text-gray-500">Location tracking tools</p>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>

    {/* Unlock Form Dialog */}
    <Dialog open={showUnlockForm} onOpenChange={setShowUnlockForm}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Unlock className="w-5 h-5 text-orange-600" />
            Unlock Device/Location
          </DialogTitle>
        </DialogHeader>
        
        <div className="space-y-4">
          <div className="bg-blue-50 p-3 rounded-lg">
            <p className="text-sm text-gray-700">
              <span className="font-medium">Account:</span> {client?.accountNumber}
            </p>
            <p className="text-sm text-gray-700">
              <span className="font-medium">Client:</span> {client?.name}
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="unlock-type">Unlock Type</Label>
            <Select value={unlockType} onValueChange={(value: "LocationUnlock" | "DeviceUnlock") => setUnlockType(value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="LocationUnlock">Location Unlock</SelectItem>
                <SelectItem value="DeviceUnlock">Device Unlock</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {unlockType === "LocationUnlock" && (
            <div>
              {accountInfo?.location && (
                <div className="bg-green-50 p-3 rounded-lg mb-3">
                  <p className="text-sm text-gray-700">
                    <span className="font-medium">Current Location:</span> {accountInfo.location}
                  </p>
                </div>
              )}
              
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label htmlFor="latitude">Latitude *</Label>
                  <Input
                    id="latitude"
                    type="text"
                    placeholder="-29.7112184"
                    value={latitude}
                    onChange={(e) => setLatitude(e.target.value)}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="longitude">Longitude *</Label>
                  <Input
                    id="longitude"
                    type="text"
                    placeholder="30.9216522"
                    value={longitude}
                    onChange={(e) => setLongitude(e.target.value)}
                  />
                </div>
              </div>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="unlock-comment">Comment *</Label>
            <Textarea
              id="unlock-comment"
              placeholder={`Enter comment for ${unlockType.toLowerCase()}...`}
              value={unlockComment}
              onChange={(e) => setUnlockComment(e.target.value)}
              rows={3}
            />
          </div>

          <div className="flex gap-2 justify-end">
            <Button
              variant="outline"
              onClick={() => setShowUnlockForm(false)}
              disabled={unlocking}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSubmitUnlock}
              disabled={unlocking || !unlockComment.trim() || (unlockType === "LocationUnlock" && (!latitude.trim() || !longitude.trim()))}
              className="bg-orange-600 hover:bg-orange-700 text-white"
            >
              {unlocking ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <Unlock className="w-4 h-4 mr-2" />
                  Submit {unlockType}
                </>
              )}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
    </>
  );
}