'use client';

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

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

export function PinLockModal({ open, isSubmitting, error, onSubmit, onLogout }: 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="relative !top-[max(1.5rem,10vh)] !-translate-y-0 [&>button]:hidden"
        onPointerDownOutside={(event) => event.preventDefault()}
        onEscapeKeyDown={(event) => event.preventDefault()}
      >
        {onLogout ? (
          <button
            type="button"
            onClick={onLogout}
            disabled={isSubmitting}
            title="Выйти из аккаунта"
            aria-label="Выйти из аккаунта"
            className="absolute left-5 top-5 flex h-9 w-9 items-center justify-center rounded-full text-[#6b6f7b] transition hover:bg-[#f4f5f8] hover:text-[#111] disabled:opacity-50"
          >
            <DoorOpen className="h-4 w-4" />
          </button>
        ) : null}

        <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">
          <PinInput
            autoFocus
            className="h-[58px] text-center text-lg tracking-[0.4em]"
            placeholder="PIN"
            value={pin}
            onChange={setPin}
            required
            minLength={4}
            maxLength={6}
          />
          {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 || !isPinInputComplete(pin)}>
            {isSubmitting ? 'Проверяем...' : 'Разблокировать'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
