import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { 
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { 
  Fingerprint, 
  Scan, 
  Shield, 
  CheckCircle, 
  AlertCircle, 
  Search,
  Download,
  Upload,
  Eye,
  Lock,
  Unlock,
  Camera,
  UserCheck,
  Settings,
  ShieldCheck,
  ShieldX,
  Database,
  Timer,
  Users,
  Key
} from "lucide-react";

export default function Biometric() {
  const { toast } = useToast();
  const [selectedPlayer, setSelectedPlayer] = useState<string>("");
  const [scanningMode, setScanningMode] = useState<string>("fingerprint");
  const [scanStatus, setScanStatus] = useState<"idle" | "scanning" | "success" | "error">("idle");
  const [facialRecognitionActive, setFacialRecognitionActive] = useState(false);
  const [cameraStream, setCameraStream] = useState<MediaStream | null>(null);
  const [privacySettings, setPrivacySettings] = useState({
    dataCollection: true,
    dataSharing: false,
    dataRetention: 365, // days
    anonymization: false,
    accessLevel: "admin-only", // admin-only, coach-access, full-access
    encryptionLevel: "high", // low, medium, high
    deletionSchedule: "manual" // manual, 30-days, 90-days, 1-year
  });

  const { data: players } = useQuery({
    queryKey: ["/api/players"],
  });

  const handleStartScan = () => {
    setScanStatus("scanning");
    // Simulate biometric scanning process
    setTimeout(() => {
      setScanStatus("success");
      setTimeout(() => setScanStatus("idle"), 3000);
    }, 3000);
  };

  const getScanStatusColor = () => {
    switch (scanStatus) {
      case "scanning": return "bg-warning";
      case "success": return "bg-success";
      case "error": return "bg-destructive";
      default: return "bg-gray-400";
    }
  };

  const getScanStatusText = () => {
    switch (scanStatus) {
      case "scanning": return "Scanning in progress...";
      case "success": return "Scan completed successfully";
      case "error": return "Scan failed - please retry";
      default: return "Ready to scan";
    }
  };

  return (
    <div className="p-6">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-3xl font-bold text-gray-900">Biometric Data Management</h2>
            <p className="text-gray-600">Secure biometric capture and identity verification for players</p>
          </div>
          <div className="flex space-x-4">
            <Dialog>
              <DialogTrigger asChild>
                <Button variant="outline">
                  <Shield className="h-4 w-4 mr-2" />
                  Privacy Settings
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle className="flex items-center space-x-2">
                    <ShieldCheck className="h-5 w-5" />
                    <span>Biometric Data Privacy Settings</span>
                  </DialogTitle>
                  <DialogDescription>
                    Configure privacy and security settings for biometric data collection and storage.
                  </DialogDescription>
                </DialogHeader>
                
                <div className="space-y-6 py-4">
                  {/* One-Click Privacy Presets */}
                  <div>
                    <h3 className="text-lg font-semibold mb-3">Quick Privacy Presets</h3>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <Button
                        variant="outline"
                        className="h-auto p-4 flex-col space-y-2"
                        onClick={() => {
                          setPrivacySettings({
                            dataCollection: true,
                            dataSharing: false,
                            dataRetention: 30,
                            anonymization: true,
                            accessLevel: "admin-only",
                            encryptionLevel: "high",
                            deletionSchedule: "30-days"
                          });
                          toast({
                            title: "Maximum Privacy Applied",
                            description: "Strict data protection settings activated"
                          });
                        }}
                      >
                        <ShieldCheck className="h-8 w-8 text-green-600" />
                        <div className="text-center">
                          <div className="font-semibold">Maximum Privacy</div>
                          <div className="text-xs text-gray-600">Strict data protection</div>
                        </div>
                      </Button>
                      
                      <Button
                        variant="outline"
                        className="h-auto p-4 flex-col space-y-2"
                        onClick={() => {
                          setPrivacySettings({
                            dataCollection: true,
                            dataSharing: false,
                            dataRetention: 365,
                            anonymization: false,
                            accessLevel: "coach-access",
                            encryptionLevel: "medium",
                            deletionSchedule: "1-year"
                          });
                          toast({
                            title: "Balanced Settings Applied",
                            description: "Privacy with functionality settings activated"
                          });
                        }}
                      >
                        <Shield className="h-8 w-8 text-blue-600" />
                        <div className="text-center">
                          <div className="font-semibold">Balanced</div>
                          <div className="text-xs text-gray-600">Privacy with functionality</div>
                        </div>
                      </Button>
                      
                      <Button
                        variant="outline"
                        className="h-auto p-4 flex-col space-y-2"
                        onClick={() => {
                          setPrivacySettings({
                            dataCollection: true,
                            dataSharing: true,
                            dataRetention: 1095,
                            anonymization: false,
                            accessLevel: "full-access",
                            encryptionLevel: "low",
                            deletionSchedule: "manual"
                          });
                          toast({
                            title: "Open Access Applied",
                            description: "Maximum functionality settings activated"
                          });
                        }}
                      >
                        <Users className="h-8 w-8 text-orange-600" />
                        <div className="text-center">
                          <div className="font-semibold">Open Access</div>
                          <div className="text-xs text-gray-600">Maximum functionality</div>
                        </div>
                      </Button>
                    </div>
                  </div>

                  {/* Detailed Settings */}
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold">Detailed Settings</h3>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <Label htmlFor="data-collection" className="flex items-center space-x-2">
                            <Database className="h-4 w-4" />
                            <span>Data Collection</span>
                          </Label>
                          <Switch
                            id="data-collection"
                            checked={privacySettings.dataCollection}
                            onCheckedChange={(checked) => setPrivacySettings(prev => ({...prev, dataCollection: checked}))}
                          />
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <Label htmlFor="data-sharing" className="flex items-center space-x-2">
                            <Users className="h-4 w-4" />
                            <span>Data Sharing</span>
                          </Label>
                          <Switch
                            id="data-sharing"
                            checked={privacySettings.dataSharing}
                            onCheckedChange={(checked) => setPrivacySettings(prev => ({...prev, dataSharing: checked}))}
                          />
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <Label htmlFor="anonymization" className="flex items-center space-x-2">
                            <ShieldX className="h-4 w-4" />
                            <span>Data Anonymization</span>
                          </Label>
                          <Switch
                            id="anonymization"
                            checked={privacySettings.anonymization}
                            onCheckedChange={(checked) => setPrivacySettings(prev => ({...prev, anonymization: checked}))}
                          />
                        </div>
                      </div>
                      
                      <div className="space-y-4">
                        <div>
                          <Label className="flex items-center space-x-2 mb-2">
                            <Key className="h-4 w-4" />
                            <span>Access Level</span>
                          </Label>
                          <Select 
                            value={privacySettings.accessLevel} 
                            onValueChange={(value) => setPrivacySettings(prev => ({...prev, accessLevel: value}))}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="admin-only">Admin Only</SelectItem>
                              <SelectItem value="coach-access">Coach Access</SelectItem>
                              <SelectItem value="full-access">Full Team Access</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        
                        <div>
                          <Label className="flex items-center space-x-2 mb-2">
                            <Shield className="h-4 w-4" />
                            <span>Encryption Level</span>
                          </Label>
                          <Select 
                            value={privacySettings.encryptionLevel} 
                            onValueChange={(value) => setPrivacySettings(prev => ({...prev, encryptionLevel: value}))}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="low">Standard</SelectItem>
                              <SelectItem value="medium">Enhanced</SelectItem>
                              <SelectItem value="high">Military Grade</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        
                        <div>
                          <Label className="flex items-center space-x-2 mb-2">
                            <Timer className="h-4 w-4" />
                            <span>Auto Deletion</span>
                          </Label>
                          <Select 
                            value={privacySettings.deletionSchedule} 
                            onValueChange={(value) => setPrivacySettings(prev => ({...prev, deletionSchedule: value}))}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="manual">Manual Only</SelectItem>
                              <SelectItem value="30-days">30 Days</SelectItem>
                              <SelectItem value="90-days">90 Days</SelectItem>
                              <SelectItem value="1-year">1 Year</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Privacy Status Summary */}
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <h4 className="font-semibold mb-2">Current Privacy Status</h4>
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div className="flex justify-between">
                        <span>Data Collection:</span>
                        <Badge variant={privacySettings.dataCollection ? "default" : "secondary"}>
                          {privacySettings.dataCollection ? "Enabled" : "Disabled"}
                        </Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>Encryption:</span>
                        <Badge variant={privacySettings.encryptionLevel === "high" ? "default" : "secondary"}>
                          {privacySettings.encryptionLevel}
                        </Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>Access Level:</span>
                        <Badge variant="outline">{privacySettings.accessLevel}</Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>Auto Deletion:</span>
                        <Badge variant="outline">{privacySettings.deletionSchedule}</Badge>
                      </div>
                    </div>
                  </div>

                  <div className="flex justify-end space-x-3">
                    <Button 
                      variant="outline" 
                      onClick={() => {
                        toast({
                          title: "Settings Saved",
                          description: "Privacy settings have been updated successfully."
                        });
                      }}
                    >
                      Save Settings
                    </Button>
                    <Button 
                      onClick={() => {
                        toast({
                          title: "Settings Applied",
                          description: "Privacy settings applied to all biometric data."
                        });
                      }}
                    >
                      Apply Now
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
            
            <Button variant="outline">
              <Download className="h-4 w-4 mr-2" />
              Export Data
            </Button>
            <Button variant="outline">
              <Upload className="h-4 w-4 mr-2" />
              Bulk Import
            </Button>
          </div>
        </div>
      </div>

      {/* Biometric Scanner Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Fingerprint className="h-5 w-5" />
              <span>Biometric Scanner</span>
            </CardTitle>
            <CardDescription>
              Capture fingerprint and facial recognition data for player identification
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Player Selection */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Select Player</label>
              <Select value={selectedPlayer} onValueChange={setSelectedPlayer}>
                <SelectTrigger>
                  <SelectValue placeholder="Choose a player to scan" />
                </SelectTrigger>
                <SelectContent>
                  {players?.map((player: any) => (
                    <SelectItem key={player.id} value={player.id.toString()}>
                      {player.firstName} {player.lastName} - {player.teamName || "No team"}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Scan Type Selection */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Biometric Type</label>
              <Select value={scanningMode} onValueChange={setScanningMode}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="fingerprint">Fingerprint Scan</SelectItem>
                  <SelectItem value="facial">Facial Recognition</SelectItem>
                  <SelectItem value="iris">Iris Scan</SelectItem>
                  <SelectItem value="palm">Palm Print</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Scanning Interface */}
            <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
              <div className={`w-24 h-24 mx-auto rounded-full flex items-center justify-center mb-4 ${getScanStatusColor()}`}>
                {scanStatus === "scanning" ? (
                  <Scan className="h-12 w-12 text-white animate-pulse" />
                ) : scanStatus === "success" ? (
                  <CheckCircle className="h-12 w-12 text-white" />
                ) : scanStatus === "error" ? (
                  <AlertCircle className="h-12 w-12 text-white" />
                ) : (
                  <Fingerprint className="h-12 w-12 text-white" />
                )}
              </div>
              <p className="text-lg font-semibold text-gray-900 mb-2">
                {getScanStatusText()}
              </p>
              <p className="text-sm text-gray-500 mb-4">
                {scanningMode === "fingerprint" && "Place finger on the scanner"}
                {scanningMode === "facial" && "Look directly at the camera"}
                {scanningMode === "iris" && "Look into the iris scanner"}
                {scanningMode === "palm" && "Place palm on the scanner"}
              </p>
              <Button 
                onClick={handleStartScan}
                disabled={!selectedPlayer || scanStatus === "scanning"}
                className="w-full"
              >
                {scanStatus === "scanning" ? "Scanning..." : `Start ${scanningMode} Scan`}
              </Button>
            </div>

            {/* Security Notice */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="flex items-start space-x-3">
                <Shield className="h-5 w-5 text-blue-600 mt-0.5" />
                <div>
                  <h4 className="text-sm font-semibold text-blue-900">Security Notice</h4>
                  <p className="text-sm text-blue-800">
                    All biometric data is encrypted and stored securely. Only authorized personnel can access this information.
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Recent Scans */}
        <Card>
          <CardHeader>
            <CardTitle>Recent Biometric Scans</CardTitle>
            <CardDescription>Latest biometric data captures and verifications</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {players?.slice(0, 5).map((player: any, index: number) => (
                <div key={player.id} className="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
                  <div className="flex items-center space-x-3">
                    <Avatar className="w-10 h-10">
                      <AvatarImage src={player.profileImageUrl} alt={`${player.firstName} ${player.lastName}`} />
                      <AvatarFallback>
                        {player.firstName[0]}{player.lastName[0]}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <h4 className="font-semibold text-gray-900">{player.firstName} {player.lastName}</h4>
                      <p className="text-sm text-gray-500">
                        Fingerprint • {new Date().toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge className="bg-green-500 text-white">
                      <CheckCircle className="h-3 w-3 mr-1" />
                      Verified
                    </Badge>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => {
                        // View biometric data
                        toast({
                          title: "Biometric Data",
                          description: `Viewing ${player.firstName} ${player.lastName}'s biometric data`
                        });
                      }}
                      className="h-8 w-8 p-0"
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => {
                        const newSettings = {
                          ...privacySettings,
                          accessLevel: privacySettings.accessLevel === "admin-only" ? "full-access" : "admin-only"
                        };
                        setPrivacySettings(newSettings);
                        toast({
                          title: "Privacy Updated",
                          description: `Access level changed to ${newSettings.accessLevel} for ${player.firstName} ${player.lastName}`
                        });
                      }}
                      className="h-8 w-8 p-0"
                    >
                      {privacySettings.accessLevel === "admin-only" ? <Lock className="h-4 w-4" /> : <Unlock className="h-4 w-4" />}
                    </Button>
                    <Button variant="ghost" size="sm">
                      <Eye className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )) || (
                <p className="text-gray-500 text-center py-8">
                  No biometric scans available. Add players to start scanning.
                </p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Biometric Database */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Biometric Database</CardTitle>
              <CardDescription>Manage and search biometric records</CardDescription>
            </div>
            <div className="flex space-x-2">
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input placeholder="Search records..." className="pl-10 w-64" />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {players?.map((player: any) => (
              <Card key={player.id} className="hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center space-x-3 mb-3">
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={player.profileImageUrl} alt={`${player.firstName} ${player.lastName}`} />
                      <AvatarFallback>
                        {player.firstName[0]}{player.lastName[0]}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <h4 className="font-semibold text-gray-900">{player.firstName} {player.lastName}</h4>
                      <p className="text-sm text-gray-500">{player.teamName || "No team"}</p>
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-gray-600">Fingerprint:</span>
                      <Badge className="bg-success text-white">
                        <CheckCircle className="h-3 w-3 mr-1" />
                        Enrolled
                      </Badge>
                    </div>
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-gray-600">Facial ID:</span>
                      <Badge className="bg-success text-white">
                        <CheckCircle className="h-3 w-3 mr-1" />
                        Enrolled
                      </Badge>
                    </div>
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-gray-600">Last Scan:</span>
                      <span className="text-gray-500">{new Date().toLocaleDateString()}</span>
                    </div>
                  </div>
                  
                  <div className="flex justify-end space-x-1 mt-4">
                    <Button variant="ghost" size="sm">
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="sm">
                      <Lock className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )) || (
              <div className="col-span-full text-center py-12">
                <Fingerprint className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">No biometric records</h3>
                <p className="text-gray-500">Add players and start scanning to build your biometric database.</p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mt-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Total Enrolled</p>
                <p className="text-3xl font-bold text-gray-900">{players?.length || 0}</p>
              </div>
              <Fingerprint className="h-8 w-8 text-primary" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Success Rate</p>
                <p className="text-3xl font-bold text-gray-900">98.7%</p>
              </div>
              <CheckCircle className="h-8 w-8 text-success" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Today's Scans</p>
                <p className="text-3xl font-bold text-gray-900">47</p>
              </div>
              <Scan className="h-8 w-8 text-secondary" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Security Level</p>
                <p className="text-3xl font-bold text-gray-900">High</p>
              </div>
              <Shield className="h-8 w-8 text-warning" />
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}