import React, { useState, useCallback, useEffect } from 'react';
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Lock, Delete } from "lucide-react";
import { toast } from "sonner";

const MAX_ATTEMPTS = 3;
const LOCKOUT_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds

const PinProtection = ({ onSuccess }) => {
    const [pin, setPin] = useState("");
    const [attempts, setAttempts] = useState(() => {
      return parseInt(localStorage.getItem('pinAttempts') || '0');
    });
    const [lockoutTime, setLockoutTime] = useState(() => {
      const lastAttempt = localStorage.getItem('lastAttemptTime');
      if (!lastAttempt) return 0;
      
      const timeSinceLastAttempt = Date.now() - parseInt(lastAttempt);
      if (timeSinceLastAttempt < LOCKOUT_DURATION) {
        return LOCKOUT_DURATION - timeSinceLastAttempt;
      }
      return 0;
    });
    useEffect(() => {
      let timer;
      if (lockoutTime > 0) {
        timer = setInterval(() => {
          setLockoutTime(prev => {
            const newTime = prev - 1000;
            if (newTime <= 0) {
              localStorage.removeItem('pinAttempts');
              localStorage.removeItem('lastAttemptTime');
              return 0;
            }
            return newTime;
          });
        }, 1000);
      }
      return () => clearInterval(timer);
    }, [lockoutTime]);
  
    const handleComplete = useCallback((value) => {
      if (lockoutTime > 0) {
        return;
      }
  
      const newAttempts = attempts + 1;
      setAttempts(newAttempts);
      localStorage.setItem('pinAttempts', newAttempts.toString());
      localStorage.setItem('lastAttemptTime', Date.now().toString());
  
      if (newAttempts >= MAX_ATTEMPTS) {
        setLockoutTime(LOCKOUT_DURATION);
        toast.error("Too many attempts", {
          description: `Please try again in ${Math.ceil(LOCKOUT_DURATION / 60000)} minutes`,
        });
        setPin("");
        return;
      }
  
      if (value === "892312") {
        toast.success("PIN accepted");
        // Reset attempts on success
        setAttempts(0);
        localStorage.removeItem('pinAttempts');
        localStorage.removeItem('lastAttemptTime');
        onSuccess();
      } else {
        toast.error(`Incorrect PIN. ${MAX_ATTEMPTS - newAttempts} attempts remaining`);
        setPin("");
      }
    }, [attempts, lockoutTime, onSuccess]);

  const handleKeyPress = (value) => {
    if (pin.length < 6) {
      const newPin = pin + value;
      setPin(newPin);
      if (newPin.length === 6) {
        handleComplete(newPin);
      }
    }
  };

  const handleDelete = () => {
    setPin(prev => prev.slice(0, -1));
  };

  const renderKeypad = () => {
    const keys = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      ['clear', 0, 'delete']
    ];

    return keys.map((row, rowIndex) => (
      <div key={rowIndex} className="flex justify-center gap-4">
        {row.map((key, index) => {
          if (key === 'delete') {
            return (
              <Button
                key={key}
                variant="ghost"
                className="w-16 h-16 text-lg font-medium text-slate-300 hover:bg-white/[0.06] hover:text-white"
                onClick={handleDelete}
              >
                <Delete className="h-6 w-6" />
              </Button>
            );
          }
          if (key === 'clear') {
            return (
              <Button
                key={key}
                variant="ghost"
                className="w-16 h-16 text-lg font-medium text-slate-300 hover:bg-white/[0.06] hover:text-white"
                onClick={() => setPin("")}
              >
                Clear
              </Button>
            );
          }
          return (
            <Button
              key={key}
              variant="ghost"
              className="w-16 h-16 text-2xl font-medium text-white hover:bg-white/[0.08] rounded-xl transition-colors"
              onClick={() => handleKeyPress(key.toString())}
            >
              {key}
            </Button>
          );
        })}
      </div>
    ));
  };

  // Create masked version of PIN
  const maskedPin = pin.replace(/./g, '•');

  return (
    <div className="min-h-screen w-screen flex items-center justify-center bg-gradient-to-br from-slate-950 via-slate-900 to-indigo-950 p-4 relative overflow-hidden">
      {/* Ambient glow */}
      <div className="absolute top-1/3 left-1/2 -translate-x-1/2 w-[400px] h-[400px] bg-indigo-500/[0.08] rounded-full blur-[100px] pointer-events-none" />

      <Card className="w-full max-w-md bg-slate-800/50 backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-2xl shadow-black/30 relative z-10">
        <CardHeader className="space-y-1">
          <div className="flex items-center justify-center mb-4">
            <div className="p-3 rounded-full bg-indigo-500/10 ring-1 ring-indigo-400/20">
              <Lock className="h-8 w-8 text-indigo-300" />
            </div>
          </div>
          <CardTitle className="text-2xl text-center text-white">Enter PIN</CardTitle>
          <CardDescription className="text-center text-slate-400">
            {lockoutTime > 0 ? (
              `Too many attempts. Try again in ${Math.ceil(lockoutTime / 60000)} minutes`
            ) : (
              "Enter your PIN to access the display"
            )}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-8">
          <div className="flex justify-center">
            <InputOTP
              maxLength={6}
              value={maskedPin}
              disabled
            >
              <InputOTPGroup>
                {[0,1,2,3,4,5].map((index) => (
                  <InputOTPSlot
                    key={index}
                    index={index}
                    className="w-14 h-14 text-2xl border-white/10 bg-white/[0.04] text-white rounded-lg"
                    readOnly
                  />
                ))}
              </InputOTPGroup>
            </InputOTP>
          </div>

          <div className="space-y-4">
            {renderKeypad()}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default PinProtection;