import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { 
  Key, 
  QrCode, 
  Smartphone,
  Clock,
  Shield,
  CheckCircle,
  AlertCircle,
  Copy,
  Send,
  Unlock,
  Lock,
  Calendar,
  RefreshCw
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface AccessCode {
  id: string;
  roomNumber: string;
  guestName: string;
  code: string;
  qrCode: string;
  validFrom: string;
  validUntil: string;
  status: 'active' | 'expired' | 'revoked';
  accessCount: number;
}

const KeylessEntry = () => {
  const { toast } = useToast();
  const [accessCodes, setAccessCodes] = useState<AccessCode[]>([
    {
      id: '1',
      roomNumber: '305',
      guestName: 'Juan Pérez',
      code: '8A9B-C4D7',
      qrCode: 'QR-305-8A9BC4D7',
      validFrom: '2025-01-15 14:00',
      validUntil: '2025-01-20 12:00',
      status: 'active',
      accessCount: 12
    },
    {
      id: '2',
      roomNumber: '412',
      guestName: 'María González',
      code: '5F2E-H8J3',
      qrCode: 'QR-412-5F2EH8J3',
      validFrom: '2025-01-14 15:00',
      validUntil: '2025-01-19 11:00',
      status: 'active',
      accessCount: 8
    }
  ]);

  const [newCodeForm, setNewCodeForm] = useState({
    roomNumber: '',
    guestName: '',
    validFrom: '',
    validUntil: ''
  });

  const generateCode = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
      if (i === 4) code += '-';
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
  };

  const handleGenerateAccessCode = () => {
    if (!newCodeForm.roomNumber || !newCodeForm.guestName) {
      toast({
        title: "Error",
        description: "Por favor completa todos los campos requeridos",
        variant: "destructive"
      });
      return;
    }

    const newCode: AccessCode = {
      id: String(accessCodes.length + 1),
      roomNumber: newCodeForm.roomNumber,
      guestName: newCodeForm.guestName,
      code: generateCode(),
      qrCode: `QR-${newCodeForm.roomNumber}-${Date.now()}`,
      validFrom: newCodeForm.validFrom || new Date().toISOString(),
      validUntil: newCodeForm.validUntil || new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
      status: 'active',
      accessCount: 0
    };

    setAccessCodes([...accessCodes, newCode]);
    
    toast({
      title: "Código Generado",
      description: `Código de acceso creado para habitación ${newCodeForm.roomNumber}`,
    });

    // Reset form
    setNewCodeForm({
      roomNumber: '',
      guestName: '',
      validFrom: '',
      validUntil: ''
    });
  };

  const copyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    toast({
      title: "Código Copiado",
      description: "El código ha sido copiado al portapapeles",
    });
  };

  const sendCode = (code: AccessCode) => {
    toast({
      title: "Código Enviado",
      description: `Código enviado a ${code.guestName} por email y SMS`,
    });
  };

  const revokeCode = (codeId: string) => {
    setAccessCodes(accessCodes.map(code => 
      code.id === codeId ? { ...code, status: 'revoked' as const } : code
    ));
    toast({
      title: "Código Revocado",
      description: "El código de acceso ha sido desactivado",
      variant: "destructive"
    });
  };

  const statusConfig = {
    active: { label: 'Activo', color: 'bg-green-100 text-green-800', icon: CheckCircle },
    expired: { label: 'Expirado', color: 'bg-gray-100 text-gray-800', icon: Clock },
    revoked: { label: 'Revocado', color: 'bg-red-100 text-red-800', icon: AlertCircle }
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Códigos Activos</p>
                <p className="text-2xl font-bold">{accessCodes.filter(c => c.status === 'active').length}</p>
              </div>
              <Key className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Accesos Hoy</p>
                <p className="text-2xl font-bold">47</p>
              </div>
              <Unlock className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Códigos QR</p>
                <p className="text-2xl font-bold">{accessCodes.length}</p>
              </div>
              <QrCode className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Seguridad</p>
                <p className="text-2xl font-bold">99.9%</p>
              </div>
              <Shield className="w-8 h-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Generate New Code */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Key className="w-5 h-5" />
            Generar Nuevo Código de Acceso
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="roomNumber">Número de Habitación *</Label>
              <Input
                id="roomNumber"
                placeholder="305"
                value={newCodeForm.roomNumber}
                onChange={(e) => setNewCodeForm({ ...newCodeForm, roomNumber: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="guestName">Nombre del Huésped *</Label>
              <Input
                id="guestName"
                placeholder="Juan Pérez"
                value={newCodeForm.guestName}
                onChange={(e) => setNewCodeForm({ ...newCodeForm, guestName: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="validFrom">Válido Desde</Label>
              <Input
                id="validFrom"
                type="datetime-local"
                value={newCodeForm.validFrom}
                onChange={(e) => setNewCodeForm({ ...newCodeForm, validFrom: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="validUntil">Válido Hasta</Label>
              <Input
                id="validUntil"
                type="datetime-local"
                value={newCodeForm.validUntil}
                onChange={(e) => setNewCodeForm({ ...newCodeForm, validUntil: e.target.value })}
              />
            </div>
          </div>
          <Button onClick={handleGenerateAccessCode} className="mt-4 w-full md:w-auto">
            <Key className="w-4 h-4 mr-2" />
            Generar Código de Acceso
          </Button>
        </CardContent>
      </Card>

      {/* Active Codes */}
      <Card>
        <CardHeader>
          <CardTitle>Códigos de Acceso Generados</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {accessCodes.map((code) => {
              const StatusIcon = statusConfig[code.status].icon;
              return (
                <div key={code.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-3">
                        <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center font-bold text-blue-600">
                          {code.roomNumber}
                        </div>
                        <div>
                          <h3 className="font-semibold text-lg">{code.guestName}</h3>
                          <p className="text-sm text-gray-600">ID: {code.id}</p>
                        </div>
                        <Badge className={statusConfig[code.status].color}>
                          <StatusIcon className="w-3 h-3 mr-1" />
                          {statusConfig[code.status].label}
                        </Badge>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                        <div className="flex items-center gap-2 p-3 bg-gray-50 rounded">
                          <Key className="w-5 h-5 text-blue-600" />
                          <div>
                            <p className="text-xs text-gray-600">Código PIN</p>
                            <p className="font-mono font-bold">{code.code}</p>
                          </div>
                          <Button 
                            size="sm" 
                            variant="ghost" 
                            onClick={() => copyCode(code.code)}
                            className="ml-auto"
                          >
                            <Copy className="w-4 h-4" />
                          </Button>
                        </div>
                        <div className="flex items-center gap-2 p-3 bg-gray-50 rounded">
                          <QrCode className="w-5 h-5 text-purple-600" />
                          <div>
                            <p className="text-xs text-gray-600">Código QR</p>
                            <p className="font-mono text-sm">{code.qrCode}</p>
                          </div>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-4 text-sm text-gray-600">
                        <div className="flex items-center gap-1">
                          <Calendar className="w-4 h-4" />
                          {code.validFrom}
                        </div>
                        <span>→</span>
                        <div className="flex items-center gap-1">
                          <Calendar className="w-4 h-4" />
                          {code.validUntil}
                        </div>
                        <div className="flex items-center gap-1 ml-auto">
                          <Unlock className="w-4 h-4" />
                          {code.accessCount} accesos
                        </div>
                      </div>
                    </div>

                    <div className="flex flex-col gap-2">
                      {code.status === 'active' && (
                        <>
                          <Button 
                            variant="outline"
                            onClick={() => sendCode(code)}
                            className="w-full md:w-auto"
                          >
                            <Send className="w-4 h-4 mr-2" />
                            Enviar
                          </Button>
                          <Button 
                            variant="destructive"
                            onClick={() => revokeCode(code.id)}
                            className="w-full md:w-auto"
                          >
                            <Lock className="w-4 h-4 mr-2" />
                            Revocar
                          </Button>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Security Info */}
      <Card className="bg-blue-50 border-blue-200">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-blue-900">
            <Shield className="w-5 h-5" />
            Seguridad del Sistema
          </CardTitle>
        </CardHeader>
        <CardContent className="text-blue-900">
          <ul className="space-y-2 text-sm">
            <li className="flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-600" />
              Códigos encriptados de 256-bit
            </li>
            <li className="flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-600" />
              Expiración automática de códigos
            </li>
            <li className="flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-600" />
              Registro de todos los accesos
            </li>
            <li className="flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-600" />
              Notificaciones en tiempo real
            </li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
};

export default KeylessEntry;
