'use client';

import * as React from 'react';
import { KeyRound } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';

interface PinLockModalProps {
  open: boolean;
  isSubmitting: boolean;
  error?: string | null;
  onSubmit: (pin: string) => Promise<void>;
}

export function PinLockModal({ open, isSubmitting, error, onSubmit }: PinLockModalProps) {
  const [pin, setPin] = React.useState('');

  React.useEffect(() => {
    if (open) {
      setPin('');
    }
  }, [open]);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    await onSubmit(pin);
  }

  return (
    <Dialog open={open} onOpenChange={() => undefined}>
      <DialogContent className="[&>button]:hidden" onPointerDownOutside={(event) => event.preventDefault()} onEscapeKeyDown={(event) => event.preventDefault()}>
        <DialogHeader>
          <div className="mx-auto mb-2 flex h-14 w-14 items-center justify-center rounded-full bg-[#f4f5f8]">
            <KeyRound className="h-7 w-7 text-[#111]" />
          </div>
          <DialogTitle className="text-center">Введите PIN-код</DialogTitle>
          <p className="text-center text-sm text-[#6b6f7b]">Сессия заблокирована из-за бездействия. Подтвердите PIN, чтобы продолжить работу.</p>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <Input
            autoFocus
            className="h-[58px] text-center text-lg tracking-[0.4em]"
            placeholder="PIN"
            value={pin}
            onChange={(event) => setPin(event.target.value)}
            required
            minLength={4}
            maxLength={6}
            inputMode="numeric"
            autoComplete="one-time-code"
          />
          {error ? <p className="text-center text-sm text-red-600">{error}</p> : null}
          <Button type="submit" size="lg" className="w-full rounded-[18px]" disabled={isSubmitting || pin.length < 4}>
            {isSubmitting ? 'Проверяем...' : 'Разблокировать'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
