import React, { useState } from 'react';
import { useForm, usePage, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { ShieldCheck, ShieldAlert, Loader2, Smartphone, Copy, Check } from 'lucide-react'; // Added Copy, Check
import { useTranslation } from '@/hooks/useTranslation';

export default function TwoFactorAuthenticationForm() {
    const { t } = useTranslation();
    const { auth } = usePage().props;
    const isEnabled = auth.user.has_2fa_enabled;

    const [enabling, setEnabling] = useState(false);
    const [qrCode, setQrCode] = useState(null);
    const [setupKey, setSetupKey] = useState(null);
    const [copied, setCopied] = useState(false); // State for copy feedback

    const { data, setData, post, processing, errors, reset } = useForm({
        code: '',
    });

    const enableTwoFactor = async () => {
        setEnabling(true);
        try {
            const res = await axios.post(route('two-factor.enable'));
            setQrCode(res.data.svg);
            setSetupKey(res.data.secret);
        } catch (error) {
            toast.error(t('Failed to initiate 2FA setup.'));
        } finally {
            setEnabling(false);
        }
    };

    const confirmTwoFactor = (e) => {
        e.preventDefault();
        post(route('two-factor.confirm'), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t('Two-factor authentication enabled successfully!'));
                setQrCode(null);
                setSetupKey(null);
                reset();
            },
        });
    };

    const disableTwoFactor = () => {
        router.delete(route('two-factor.disable'), {
            preserveScroll: true,
            onSuccess: () => toast.success(t('Two-factor authentication disabled.'))
        });
    };

    // Helper function to copy key
    const copyToClipboard = () => {
        if (!setupKey) return;
        navigator.clipboard.writeText(setupKey);
        setCopied(true);
        toast.success(t('Setup key copied to clipboard!'));
        setTimeout(() => setCopied(false), 2000);
    };

    return (
        <section className="space-y-6">
            <header className="mb-6">
                <h2 className="text-lg font-bold flex items-center gap-2">
                    <Smartphone className="w-5 h-5 text-primary" /> 
                    {t('Two-Factor Authentication (2FA)')}
                </h2>
                <p className="mt-1 text-sm text-muted-foreground">
                    {t('Add additional security to your account using two-factor authentication.')}
                </p>
            </header>

            {!isEnabled && !qrCode && (
                <div>
                    <div className="p-4 rounded-xl bg-amber-500/10 border border-amber-500/20 flex gap-3 items-start mb-4">
                        <ShieldAlert className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
                        <div>
                            <p className="font-bold text-amber-700 dark:text-amber-500 text-sm">
                                {t('You have not enabled two-factor authentication.')}
                            </p>
                            <p className="text-sm text-amber-600/90 dark:text-amber-400/90 mt-1">
                                {t('When two-factor authentication is enabled, you will be prompted for a secure, random token during authentication. You may retrieve this token from your phone\'s Google Authenticator application.')}
                            </p>
                        </div>
                    </div>
                    <Button onClick={enableTwoFactor} disabled={enabling} className="font-bold">
                        {enabling && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                        {t('Enable 2FA')}
                    </Button>
                </div>
            )}

            {qrCode && (
                <div className="space-y-6">
                    <p className="text-sm font-semibold text-foreground">
                        {t('To finish enabling two-factor authentication, scan the following QR code using your phone\'s authenticator application or enter the setup key and provide the generated OTP code.')}
                    </p>

                    <div className="flex flex-col sm:flex-row items-center gap-6">
                        <div className="p-2 bg-white rounded-xl shadow-sm border" dangerouslySetInnerHTML={{ __html: qrCode }} />
                        <div className="space-y-2 w-full sm:max-w-xs">
                            <Label className="text-xs uppercase tracking-widest text-muted-foreground font-bold">{t('Setup Key')}</Label>
                            
                            {/* UPDATED: Setup Key with Copy Button */}
                            <div className="relative group">
                                <div className="font-mono bg-muted p-3 pr-10 rounded border text-sm text-center font-black tracking-widest break-all">
                                    {setupKey}
                                </div>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={copyToClipboard}
                                    className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 hover:bg-background"
                                    title={t('Copy Key')}
                                >
                                    {copied ? (
                                        <Check className="h-4 w-4 text-green-600" />
                                    ) : (
                                        <Copy className="h-4 w-4 text-muted-foreground" />
                                    )}
                                </Button>
                            </div>
                            <p className="text-[10px] text-muted-foreground italic text-center">{t('Manual entry key for apps')}</p>
                        </div>
                    </div>

                    <form onSubmit={confirmTwoFactor} className="space-y-4 max-w-sm pt-4 border-t">
                        <div className="space-y-2">
                            <Label htmlFor="code" className="font-bold">{t('Verify Code')}</Label>
                            <Input
                                id="code"
                                type="text"
                                inputMode="numeric"
                                placeholder="123456"
                                value={data.code}
                                onChange={(e) => setData('code', e.target.value.replace(/[^0-9]/g, ''))}
                                className={`text-center tracking-[0.5em] font-mono text-lg h-12 bg-background ${errors.code ? "border-destructive" : ""}`}
                                autoFocus
                                required
                            />
                            {errors.code && <p className="text-xs text-destructive font-bold">{errors.code}</p>}
                        </div>
                        <div className="flex gap-2">
                            <Button type="submit" disabled={processing || data.code.length !== 6} className="font-bold flex-1">
                                {processing && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} {t('Confirm & Enable')}
                            </Button>
                            <Button type="button" variant="outline" onClick={() => { setQrCode(null); setSetupKey(null); }} className="flex-1">
                                {t('Cancel')}
                            </Button>
                        </div>
                    </form>
                </div>
            )}

            {isEnabled && (
                <div>
                    <div className="p-4 rounded-xl bg-green-500/10 border border-green-500/20 flex gap-3 items-start mb-4">
                        <ShieldCheck className="w-5 h-5 text-green-600 shrink-0 mt-0.5" />
                        <div>
                            <p className="font-bold text-green-700 dark:text-green-500 text-sm">
                                {t('Two-factor authentication is enabled.')}
                            </p>
                            <p className="text-sm text-green-600/90 dark:text-green-400/90 mt-1">
                                {t('Your account is now highly secure. You will be asked for a code every time you log in.')}
                            </p>
                        </div>
                    </div>
                    <Button variant="destructive" onClick={disableTwoFactor} className="font-bold">
                        {t('Disable 2FA')}
                    </Button>
                </div>
            )}
        </section>
    );
}