import React, { useState, useEffect } from 'react';
import { Plus, Trash2 } from 'lucide-react';

interface PromptTemplate {
    id: string;
    name: string;
    content: string;
}

interface SettingsProps {
    onSave: (apiKey: string, productId: string, prompts: PromptTemplate[]) => void;
    onBack: () => void; // New onBack prop
    initialApiKey: string;
    initialProductId: string;
    initialPrompts: PromptTemplate[];
}

const Settings: React.FC<SettingsProps> = ({ onSave, onBack, initialApiKey, initialProductId, initialPrompts }) => {
    const [apiKey, setApiKey] = useState(initialApiKey);
    const [productId, setProductId] = useState(initialProductId);
    const [prompts, setPrompts] = useState<PromptTemplate[]>(initialPrompts);

    useEffect(() => {
        setApiKey(initialApiKey);
        setProductId(initialProductId);
        // Only reset prompts if passed different ones (mounting), usually state is preserved in App
    }, [initialApiKey, initialProductId]);

    const handleSave = (e: React.FormEvent) => {
        e.preventDefault();
        onSave(apiKey, productId, prompts);
    };

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

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

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

    return (
        <div className="p-6 w-full max-w-2xl mx-auto mt-6 animate-in fade-in duration-500">
            <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold text-foreground">Infomaniak Settings</h2>
                <button
                    type="button"
                    onClick={onBack}
                    className="text-sm text-muted-foreground hover:text-foreground hover:bg-secondary px-3 py-1.5 rounded-md transition-colors"
                >
                    Back to Recorder
                </button>
            </div>
            <form onSubmit={handleSave} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label htmlFor="apiKey" className="block text-sm font-medium mb-1 text-foreground">
                            Infomaniak API Key
                        </label>
                        <input
                            id="apiKey"
                            type="password"
                            value={apiKey}
                            onChange={(e) => setApiKey(e.target.value)}
                            placeholder="ik_..."
                            className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none"
                        />
                    </div>
                    <div>
                        <label htmlFor="productId" className="block text-sm font-medium mb-1 text-foreground">
                            Product ID
                        </label>
                        <input
                            id="productId"
                            type="text"
                            value={productId}
                            onChange={(e) => setProductId(e.target.value)}
                            placeholder="Number (e.g., 12345)"
                            className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none"
                        />
                    </div>
                </div>

                <div className="border-t border-border pt-6">
                    <div className="flex justify-between items-center mb-4">
                        <label className="block text-sm font-medium text-foreground">
                            Summarization Templates
                        </label>
                        <button
                            type="button"
                            onClick={addPrompt}
                            className="text-xs flex items-center gap-1 bg-secondary hover:bg-secondary/80 text-foreground px-3 py-1 rounded transition-colors"
                        >
                            <Plus size={14} /> Add Template
                        </button>
                    </div>

                    <div className="space-y-4 max-h-[400px] overflow-y-auto pr-2">
                        {prompts.map((prompt) => (
                            <div key={prompt.id} className="p-4 rounded-lg border border-border bg-card shadow-sm space-y-3">
                                <div className="flex justify-between gap-3">
                                    <input
                                        type="text"
                                        value={prompt.name}
                                        onChange={(e) => updatePrompt(prompt.id, 'name', e.target.value)}
                                        placeholder="Template Name (e.g., Email Summary)"
                                        className="flex-1 font-semibold bg-transparent border-none p-0 focus:ring-0 text-foreground placeholder:text-muted-foreground outline-none"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => removePrompt(prompt.id)}
                                        className="text-muted-foreground hover:text-destructive transition-colors"
                                        title="Remove Template"
                                    >
                                        <Trash2 size={16} />
                                    </button>
                                </div>
                                <textarea
                                    value={prompt.content}
                                    onChange={(e) => updatePrompt(prompt.id, 'content', e.target.value)}
                                    placeholder="Enter instructions for the AI..."
                                    rows={3}
                                    className="w-full p-2 text-sm rounded border border-border bg-secondary/50 text-foreground focus:ring-1 focus:ring-primary outline-none resize-none"
                                />
                            </div>
                        ))}
                        {prompts.length === 0 && (
                            <p className="text-center text-sm text-muted-foreground py-4">
                                No templates defined. Click "Add Template" to create one.
                            </p>
                        )}
                    </div>
                </div>

                <div className="flex gap-4">
                    <button
                        type="button"
                        onClick={onBack}
                        className="w-1/3 bg-secondary text-secondary-foreground py-3 px-4 rounded-lg hover:bg-secondary/80 transition-all font-semibold"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        className="w-2/3 bg-primary text-primary-foreground py-3 px-4 rounded-lg hover:bg-primary/90 transition-all font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
                    >
                        Save Configuration
                    </button>
                </div>
            </form>
        </div>
    );
};

export default Settings;
