import React, { useState } from 'react';
import { Save, FolderOpen, Lock, Upload, Download, Eye, EyeOff } from 'lucide-react';
import { open } from '@tauri-apps/plugin-dialog';
import { encryptData, decryptData } from '../utils/backup';
import { PromptTemplate } from '../App';

interface SettingsProps {
    apiKey: string;
    productId: string;
    savePath: string;
    prompts: PromptTemplate[];
    onSave: (apiKey: string, productId: string, prompts: PromptTemplate[], savePath: string) => void;
    onClose: () => void;
}

const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePath, onSave, onClose }) => {
    const [localApiKey, setLocalApiKey] = useState(apiKey);
    const [localProductId, setLocalProductId] = useState(productId);
    const [localSavePath, setLocalSavePath] = useState(savePath);
    const [localPrompts, setLocalPrompts] = useState<PromptTemplate[]>(prompts);
    const [statusIdx, setStatusIdx] = useState<string | null>(null);

    // Backup & Restore State
    const [backupPassword, setBackupPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isImportModalOpen, setIsImportModalOpen] = useState(false);
    const [importFileContent, setImportFileContent] = useState<string | null>(null);

    const handlePromptChange = (id: string, field: 'name' | 'content', value: string) => {
        setLocalPrompts(localPrompts.map(p => p.id === id ? { ...p, [field]: value } : p));
    };

    const addPrompt = () => {
        setLocalPrompts([...localPrompts, { id: Date.now().toString(), name: 'New Prompt', content: '' }]);
    };

    const removePrompt = (id: string) => {
        setLocalPrompts(localPrompts.filter(p => p.id !== id));
    };

    const handleSave = () => {
        onSave(localApiKey, localProductId, localPrompts, localSavePath);
        onClose();
    };

    const handleSelectFolder = async () => {
        try {
            const selected = await open({
                directory: true,
                multiple: false,
                defaultPath: localSavePath || undefined,
            });
            if (selected && typeof selected === 'string') {
                setLocalSavePath(selected);
            }
        } catch (e) {
            console.error("Failed to open directory picker", e);
            setStatusIdx('Error: Failed to open directory picker.');
        }
    };

    const handleExport = async () => {
        if (!backupPassword) {
            setStatusIdx('Error: Password required to encrypt backup.');
            return;
        }
        try {
            const data = {
                apiKey: localApiKey,
                productId: localProductId,
                prompts: localPrompts,
                savePath: localSavePath
            };
            const encrypted = await encryptData(data, backupPassword);
            const blob = new Blob([encrypted], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `hearbit_backup_${new Date().toISOString().slice(0, 10)}.conf`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            setStatusIdx('Configuration exported successfully!');
        } catch (e) {
            console.error(e);
            setStatusIdx('Export failed.');
        }
    };

    const triggerImport = () => {
        document.getElementById('import-file-input')?.click();
    };

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

        const reader = new FileReader();
        reader.onload = (event) => {
            if (event.target?.result) {
                setImportFileContent(event.target.result as string);
                setIsImportModalOpen(true);
                setBackupPassword('');
            }
        };
        reader.readAsText(file);
        e.target.value = '';
    };

    const confirmImport = async () => {
        if (!backupPassword) {
            setStatusIdx('Error: Password required to decrypt.');
            return;
        }
        if (!importFileContent) return;

        try {
            const data = await decryptData(importFileContent, backupPassword);
            if (data.apiKey) setLocalApiKey(data.apiKey);
            if (data.productId) setLocalProductId(data.productId);
            if (data.prompts) setLocalPrompts(data.prompts);
            if (data.savePath) setLocalSavePath(data.savePath);

            setStatusIdx('Configuration imported! Click Save to apply.');
            setIsImportModalOpen(false);
            setImportFileContent(null);
        } catch (e) {
            console.error(e);
            setStatusIdx('Import failed: Wrong password or corrupted file.');
        }
    };

    return (
        <div className="flex flex-col h-full bg-background font-mono text-sm relative">
            {/* Import Password Modal */}
            {isImportModalOpen && (
                <div className="absolute inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
                    <div className="bg-background border border-border rounded-lg shadow-xl p-6 w-full max-w-sm space-y-4">
                        <div className="flex items-center gap-2 text-foreground font-semibold">
                            <Lock size={16} /> Import Configuration
                        </div>
                        <p className="text-muted-foreground text-xs">
                            Enter the password used to encrypt this backup file.
                        </p>
                        <div className="relative">
                            <input
                                type={showPassword ? "text" : "password"}
                                value={backupPassword}
                                onChange={(e) => setBackupPassword(e.target.value)}
                                placeholder="Backup Password"
                                className="w-full p-2 pr-8 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none"
                            />
                            <button
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute right-2 top-2.5 text-muted-foreground hover:text-foreground"
                            >
                                {showPassword ? <EyeOff size={14} /> : <Eye size={14} />}
                            </button>
                        </div>
                        <div className="flex justify-end gap-2 pt-2">
                            <button
                                onClick={() => setIsImportModalOpen(false)}
                                className="px-3 py-1.5 text-xs font-medium rounded border border-border hover:bg-secondary text-foreground transition-colors"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={confirmImport}
                                disabled={!backupPassword}
                                className="px-3 py-1.5 text-xs font-medium rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
                            >
                                Decrypt & Import
                            </button>
                        </div>
                    </div>
                </div>
            )}

            <div className="p-4 border-b border-border/40 bg-secondary/20 flex justify-between items-center">
                <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Settings</span>
                <button onClick={handleSave} className="flex items-center gap-1 text-primary hover:text-primary/80 transition-colors font-semibold">
                    <Save size={16} /> Save
                </button>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-6">
                <div className="space-y-4 border rounded p-4 border-border/50">
                    <h3 className="text-foreground font-semibold flex items-center gap-2">General</h3>
                    <div>
                        <label htmlFor="apiKey" className="block text-sm font-medium mb-1 text-foreground">API Key</label>
                        <input
                            id="apiKey"
                            type="password"
                            value={localApiKey}
                            onChange={(e) => setLocalApiKey(e.target.value)}
                            className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
                        />
                    </div>
                    <div>
                        <label htmlFor="productId" className="block text-sm font-medium mb-1 text-foreground">Product ID</label>
                        <input
                            id="productId"
                            type="text"
                            value={localProductId}
                            onChange={(e) => setLocalProductId(e.target.value)}
                            className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
                        />
                    </div>
                    <div>
                        <label htmlFor="savePath" className="block text-sm font-medium mb-1 text-foreground">Custom Recordings Folder</label>
                        <div className="flex gap-2">
                            <input
                                id="savePath"
                                type="text"
                                value={localSavePath}
                                onChange={(e) => setLocalSavePath(e.target.value)}
                                placeholder="/Users/username/Desktop/Recordings"
                                className="flex-1 p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
                            />
                            <button
                                onClick={handleSelectFolder}
                                className="p-2 aspect-square flex items-center justify-center bg-secondary hover:bg-secondary/80 border border-border rounded text-foreground transition-colors"
                                title="Pick Folder"
                            >
                                <FolderOpen size={16} />
                            </button>
                        </div>
                    </div>
                </div>

                <div className="space-y-4 border rounded p-4 border-border/50">
                    <h3 className="text-foreground font-semibold flex items-center gap-2">
                        <Lock size={16} /> Backup & Restore
                    </h3>
                    <p className="text-xs text-muted-foreground">
                        Export your settings (keys, prompts, path) to an encrypted file.
                    </p>

                    <div className="relative">
                        <input
                            type={showPassword ? "text" : "password"}
                            value={backupPassword}
                            onChange={(e) => setBackupPassword(e.target.value)}
                            placeholder="Encryption Password"
                            className="w-full p-2 pr-8 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none text-sm"
                        />
                        <button
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-2 top-2.5 text-muted-foreground hover:text-foreground"
                        >
                            {showPassword ? <EyeOff size={14} /> : <Eye size={14} />}
                        </button>
                    </div>

                    <div className="flex gap-2 pt-2">
                        <button
                            onClick={handleExport}
                            className="flex-1 flex items-center justify-center gap-2 py-2 px-4 rounded bg-secondary hover:bg-secondary/80 border border-border text-foreground transition-all text-xs font-semibold"
                        >
                            <Download size={14} /> Export Config
                        </button>
                        <button
                            onClick={triggerImport}
                            className="flex-1 flex items-center justify-center gap-2 py-2 px-4 rounded bg-secondary hover:bg-secondary/80 border border-border text-foreground transition-all text-xs font-semibold"
                        >
                            <Upload size={14} /> Import Config
                        </button>
                        <input
                            type="file"
                            id="import-file-input"
                            accept=".conf"
                            className="hidden"
                            onChange={handleFileSelect}
                        />
                    </div>
                </div>

                <div className="space-y-4 border rounded p-4 border-border/50">
                    <div className="flex justify-between items-center">
                        <h3 className="text-foreground font-semibold">Prompts</h3>
                        <button onClick={addPrompt} className="text-xs bg-primary text-primary-foreground px-2 py-1 rounded hover:bg-primary/90">
                            + Add Prompt
                        </button>
                    </div>
                    {localPrompts.map((prompt) => (
                        <div key={prompt.id} className="space-y-2 p-3 bg-secondary/30 rounded border border-border/50 relative group">
                            <button
                                onClick={() => removePrompt(prompt.id)}
                                className="absolute top-2 right-2 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity text-xs"
                            >
                                <EyeOff size={12} className="inline mr-1" /> Remove
                            </button>
                            <input
                                type="text"
                                value={prompt.name}
                                onChange={(e) => handlePromptChange(prompt.id, 'name', e.target.value)}
                                className="w-full p-1 bg-transparent border-b border-border/50 focus:border-primary outline-none font-semibold text-sm"
                                placeholder="Prompt Name"
                            />
                            <textarea
                                value={prompt.content}
                                onChange={(e) => handlePromptChange(prompt.id, 'content', e.target.value)}
                                className="w-full p-2 bg-secondary/50 rounded border border-border/30 focus:border-primary outline-none text-xs resize-y min-h-[60px]"
                                placeholder="Prompt Content"
                            />
                        </div>
                    ))}
                </div>

                {statusIdx && (
                    <div className={`p-2 text-xs rounded border ${statusIdx.includes('Error') || statusIdx.includes('failed') ? 'bg-destructive/10 border-destructive text-destructive' : 'bg-green-500/10 border-green-500 text-green-500'}`}>
                        {statusIdx}
                    </div>
                )}
            </div>
        </div>
    );
};

export default Settings;
