import React, { useContext, useRef, useState, useEffect } from 'react';
import { SettingsIcon, AlertTriangleIcon, Trash2Icon, KeyIcon } from '../components/icons';
import { AuthContext } from '../context/AuthContext';
import { useLocalStorage } from '../hooks/useLocalStorage';
import type { BonsaiTree, UserTool } from '../types';
import { reinitializeAI } from '../services/geminiService';

const SettingsView: React.FC = () => {
    const { logout, updateCredentials } = useContext(AuthContext);
    const [, setTrees] = useLocalStorage<BonsaiTree[]>('bonsai-diary-trees', []);
    const [, setToolkit] = useLocalStorage<UserTool[]>('user-toolkit', []);
    const importFileRef = useRef<HTMLInputElement>(null);

    const [apiKey, setApiKey] = useState('');
    const [saveStatus, setSaveStatus] = useState<'idle' | 'saved'>('idle');

    // State for credentials change
    const [currentPassword, setCurrentPassword] = useState('');
    const [newLoginName, setNewLoginName] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [credentialStatus, setCredentialStatus] = useState<{ type: 'idle' | 'success' | 'error', message: string }>({ type: 'idle', message: '' });
    const [isUpdatingCreds, setIsUpdatingCreds] = useState(false);

    useEffect(() => {
        const storedKey = window.localStorage.getItem('gemini-api-key') || '';
        setApiKey(storedKey);
    }, []);

    const handleSaveKey = () => {
        window.localStorage.setItem('gemini-api-key', apiKey);
        reinitializeAI();
        setSaveStatus('saved');
        setTimeout(() => setSaveStatus('idle'), 2000);
    };

    const handleClearKey = () => {
        if (window.confirm('Are you sure you want to clear your API key?')) {
            window.localStorage.removeItem('gemini-api-key');
            setApiKey('');
            reinitializeAI();
        }
    };
    
    const handleCredentialChange = (e: React.FormEvent) => {
        e.preventDefault();
        setIsUpdatingCreds(true);
        const result = updateCredentials(currentPassword, newLoginName, newPassword);
        if (result.success) {
            setCredentialStatus({ type: 'success', message: "Credentials updated! You will be logged out to sign in again." });
            setTimeout(() => {
                logout();
            }, 2000);
        } else {
            setCredentialStatus({ type: 'error', message: result.message });
            setTimeout(() => setCredentialStatus({ type: 'idle', message: '' }), 3000);
            setIsUpdatingCreds(false);
        }
    };

    const handleExport = () => {
        const treeKey = `yuki-app-bonsai-diary-trees`;
        const toolKey = `yuki-app-user-toolkit`;

        const data = {
            trees: JSON.parse(window.localStorage.getItem(treeKey) || '[]'),
            toolkit: JSON.parse(window.localStorage.getItem(toolKey) || '[]'),
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `yuki-bonsai-backup-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const text = e.target?.result;
                if (typeof text !== 'string') throw new Error("File is not readable");
                const data = JSON.parse(text);

                if (Array.isArray(data.trees) && Array.isArray(data.toolkit)) {
                    if(window.confirm("This will overwrite your current data. Are you sure you want to proceed?")) {
                        setTrees(data.trees);
                        setToolkit(data.toolkit);
                        alert("Data imported successfully!");
                    }
                } else {
                    throw new Error("Invalid file format.");
                }
            } catch (err) {
                alert(`Failed to import data: ${err instanceof Error ? err.message : "Unknown error"}`);
            }
        };
        reader.readAsText(file);
        event.target.value = ''; // Reset file input
    };

    const handleDelete = () => {
        if (window.confirm("DANGER: Are you absolutely sure you want to delete all your trees and toolkit data? This action cannot be undone.")) {
            if (window.confirm("FINAL WARNING: This is your last chance. All data will be permanently deleted. Continue?")) {
                setTrees([]);
                setToolkit([]);
                alert("All your data has been deleted.");
                logout();
            }
        }
    };


    return (
        <div className="space-y-8 max-w-2xl mx-auto">
            <header className="text-center">
                <h2 className="text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl flex items-center justify-center gap-3">
                    <SettingsIcon className="w-8 h-8 text-stone-600" />
                    Settings
                </h2>
                <p className="mt-4 text-lg leading-8 text-stone-600">
                    Manage your application data and preferences.
                </p>
            </header>
            
            <div className="bg-white p-6 rounded-xl shadow-lg border border-stone-200 space-y-4">
                <h3 className="text-xl font-semibold text-stone-800 flex items-center gap-2"><KeyIcon className="w-5 h-5"/> Change Login Credentials</h3>
                <p className="text-sm text-stone-600">
                    Update your login name and secret password. If you haven't set custom credentials yet, the "Current Secret Password" is the one you originally received. After updating, you will be logged out.
                </p>
                <form onSubmit={handleCredentialChange} className="space-y-3">
                    <div>
                        <label className="text-sm font-medium text-stone-700">Current Secret Password</label>
                        <input
                            type="password"
                            value={currentPassword}
                            onChange={(e) => setCurrentPassword(e.target.value)}
                            className="mt-1 block w-full rounded-md border-0 py-2 px-3 text-stone-900 shadow-sm ring-1 ring-inset ring-stone-300 focus:ring-2 focus:ring-inset focus:ring-green-600"
                            required
                        />
                    </div>
                    <div>
                        <label className="text-sm font-medium text-stone-700">New Login Name</label>
                        <input
                            type="text"
                            value={newLoginName}
                            onChange={(e) => setNewLoginName(e.target.value)}
                            className="mt-1 block w-full rounded-md border-0 py-2 px-3 text-stone-900 shadow-sm ring-1 ring-inset ring-stone-300 focus:ring-2 focus:ring-inset focus:ring-green-600"
                            placeholder="e.g., my-bonsai-corner"
                            required
                        />
                    </div>
                    <div>
                        <label className="text-sm font-medium text-stone-700">New Secret Password</label>
                        <input
                            type="password"
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            className="mt-1 block w-full rounded-md border-0 py-2 px-3 text-stone-900 shadow-sm ring-1 ring-inset ring-stone-300 focus:ring-2 focus:ring-inset focus:ring-green-600"
                            placeholder="Enter a strong new password"
                            required
                        />
                    </div>
                    <button type="submit" disabled={isUpdatingCreds} className="w-full bg-green-700 text-white font-semibold py-2 px-4 rounded-lg hover:bg-green-600 disabled:bg-stone-400">
                        {isUpdatingCreds ? 'Updating...' : 'Update Credentials & Log Out'}
                    </button>
                    {credentialStatus.type === 'success' && <p className="text-sm text-center text-green-600">{credentialStatus.message}</p>}
                    {credentialStatus.type === 'error' && <p className="text-sm text-center text-red-600">{credentialStatus.message}</p>}
                </form>
            </div>

            <div className="bg-white p-6 rounded-xl shadow-lg border border-stone-200 space-y-4">
                <h3 className="text-xl font-semibold text-stone-800">Gemini API Key</h3>
                <p className="text-sm text-stone-600">
                    To use the AI features, you need a Google Gemini API key. You can generate a free key from{' '}
                    <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer" className="font-semibold text-green-700 hover:underline">
                        Google AI Studio
                    </a>.
                </p>
                <div className="flex items-center gap-2">
                    <input 
                        type="password"
                        value={apiKey}
                        onChange={(e) => setApiKey(e.target.value)}
                        className="block w-full rounded-md border-0 py-2 px-3 text-stone-900 shadow-sm ring-1 ring-inset ring-stone-300 placeholder:text-stone-400 focus:ring-2 focus:ring-inset focus:ring-green-600 sm:text-sm sm:leading-6"
                        placeholder="Enter your Gemini API key"
                    />
                    <button onClick={handleSaveKey} className="bg-green-700 text-white font-semibold py-2 px-4 rounded-lg hover:bg-green-600 whitespace-nowrap">
                        {saveStatus === 'saved' ? 'Saved!' : 'Save Key'}
                    </button>
                    <button onClick={handleClearKey} title="Clear API Key" className="bg-stone-200 text-stone-700 p-2 rounded-lg hover:bg-stone-300">
                        <Trash2Icon className="w-5 h-5"/>
                    </button>
                </div>
            </div>

            <div className="bg-white p-6 rounded-xl shadow-lg border border-stone-200 space-y-4">
                <h3 className="text-xl font-semibold text-stone-800">Data Management</h3>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <button onClick={handleExport} className="p-4 bg-blue-100 text-blue-700 font-semibold rounded-lg hover:bg-blue-200 transition-colors">
                        Export My Data
                    </button>
                    <button onClick={() => importFileRef.current?.click()} className="p-4 bg-green-100 text-green-700 font-semibold rounded-lg hover:bg-green-200 transition-colors">
                        Import Data
                    </button>
                     <input type="file" ref={importFileRef} onChange={handleImport} accept=".json" className="hidden" />
                </div>
            </div>

             <div className="bg-red-50 p-6 rounded-xl shadow-lg border border-red-200 space-y-3">
                <div className="flex items-center gap-3">
                    <AlertTriangleIcon className="w-8 h-8 text-red-600 flex-shrink-0" />
                    <div>
                        <h3 className="text-xl font-semibold text-red-800">Danger Zone</h3>
                        <p className="text-sm text-red-700">This action is irreversible. Please export your data first if you want to keep a backup.</p>
                    </div>
                </div>
                 <button onClick={handleDelete} className="w-full p-4 bg-red-600 text-white font-bold rounded-lg hover:bg-red-700 transition-colors">
                    Delete All My Data & Log Out
                </button>
            </div>
        </div>
    );
};

export default SettingsView;