'use client';

import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { Smartphone, Plus, Trash2, Loader2, ShieldCheck, QrCode } from 'lucide-react';
import { twoFaApi } from '@/lib/api';
import { Device } from '@/types';

export default function SecurityPage() {
  const [devices, setDevices] = useState<Device[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddFlow, setShowAddFlow] = useState(false);
  const [qrCode, setQrCode] = useState('');
  const [secret, setSecret] = useState('');
  const [otp, setOtp] = useState('');
  const [deviceName, setDeviceName] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const limit = 2;

  const fetchDevices = async () => {
    setIsLoading(true);
    try {
      const res = await twoFaApi.devices();
      setDevices(res.data.devices ?? []);
    } catch {
      toast.error('Failed to load devices');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => { fetchDevices(); }, []);

  const startAddDevice = async () => {
    try {
      const res = await twoFaApi.reEnrol();
      setQrCode(res.data.qr_code);
      setSecret(res.data.secret);
      setShowAddFlow(true);
      setOtp('');
      setDeviceName('');
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to generate QR code');
    }
  };

  const confirmAddDevice = async () => {
    if (otp.length !== 6) {
      toast.error('Enter 6-digit OTP');
      return;
    }
    setIsSubmitting(true);
    try {
      await twoFaApi.confirmReEnrol(otp, deviceName || 'New Device');
      toast.success('Device added');
      setShowAddFlow(false);
      fetchDevices();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Invalid OTP');
    } finally {
      setIsSubmitting(false);
    }
  };

  const removeDevice = async (deviceId: string) => {
    if (!confirm('Remove this authenticator device?')) return;
    try {
      await twoFaApi.removeDevice(deviceId);
      toast.success('Device removed');
      fetchDevices();
    } catch {
      toast.error('Failed to remove device');
    }
  };

  return (
    <div className="max-w-2xl">
      <h1 className="text-xl font-semibold mb-2">Security & 2FA</h1>
      <p className="text-sm text-ts-muted mb-6">
        Manage your two-factor authentication devices. Up to {limit} devices are allowed.
      </p>

      {/* Status banner */}
      <div className="ts-card p-4 mb-5 flex items-center gap-3">
        <div className="w-9 h-9 rounded-lg bg-green-500/10 flex items-center justify-center shrink-0">
          <ShieldCheck size={18} className="text-green-400" />
        </div>
        <div>
          <p className="text-sm font-medium text-ts-text">Two-factor authentication is active</p>
          <p className="text-xs text-ts-muted">{devices.length}/{limit} device{devices.length !== 1 ? 's' : ''} registered</p>
        </div>
      </div>

      {/* Device list */}
      <div className="ts-card mb-5">
        {isLoading ? (
          <div className="flex justify-center py-8">
            <Loader2 className="animate-spin text-ts-muted" size={24} />
          </div>
        ) : devices.length === 0 ? (
          <div className="text-center py-10 text-ts-muted">
            <Smartphone size={28} className="mx-auto mb-2 opacity-30" />
            <p className="text-sm">No devices registered</p>
          </div>
        ) : (
          <ul className="divide-y divide-ts-border">
            {devices.map((device) => (
              <li key={device.id} className="flex items-center justify-between px-5 py-4">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-lg bg-ts-accent/10 flex items-center justify-center">
                    <Smartphone size={17} className="text-ts-accent" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-ts-text">{device.name}</p>
                    <p className="text-xs text-ts-muted">
                      Added {new Date(device.added_at).toLocaleDateString()}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => removeDevice(device.id)}
                  className="ts-btn-ghost p-2 hover:text-red-400 hover:bg-red-400/5"
                >
                  <Trash2 size={15} />
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Add device */}
      {devices.length < limit && !showAddFlow && (
        <button onClick={startAddDevice} className="ts-btn-primary flex items-center gap-2">
          <Plus size={16} />
          Add Authenticator Device
        </button>
      )}

      {/* Add device flow */}
      {showAddFlow && (
        <div className="ts-card p-6">
          <h2 className="font-medium mb-1 flex items-center gap-2">
            <QrCode size={16} className="text-ts-accent" />
            Add New Device
          </h2>
          <p className="text-xs text-ts-muted mb-4">
            Scan the QR code with your authenticator app (Google Authenticator, Authy), then enter the code below.
          </p>

          {qrCode && (
            <div className="flex justify-center mb-4">
              <img src={qrCode} alt="QR Code" className="w-44 h-44 rounded" />
            </div>
          )}
          {secret && (
            <div className="bg-ts-bg rounded p-2 text-center mb-4">
              <p className="text-xs text-ts-muted mb-1">Manual key</p>
              <code className="text-xs font-mono text-ts-accent">{secret}</code>
            </div>
          )}

          <div className="space-y-3">
            <div>
              <label className="ts-label">Device Name</label>
              <input
                value={deviceName}
                onChange={(e) => setDeviceName(e.target.value)}
                className="ts-input"
                placeholder="e.g. iPhone 15 Pro"
              />
            </div>
            <div>
              <label className="ts-label">Verification Code</label>
              <input
                value={otp}
                onChange={(e) => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                className="ts-input text-center font-mono text-lg tracking-widest"
                placeholder="000000"
                maxLength={6}
              />
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setShowAddFlow(false)}
                className="ts-btn-ghost flex-1"
              >
                Cancel
              </button>
              <button
                onClick={confirmAddDevice}
                disabled={isSubmitting || otp.length !== 6}
                className="ts-btn-primary flex-1 flex items-center justify-center gap-2"
              >
                {isSubmitting && <Loader2 size={15} className="animate-spin" />}
                Confirm Device
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
