import { useEffect, useRef, useState } from 'react';
import { RichTextEditor } from 'react-summernote-light';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Info } from 'lucide-react';

interface LetterheadEditorProps {
    value: string;
    onChange: (value: string) => void;
    type: 'header' | 'footer';
    height?: string;
}

export default function LetterheadEditor({ value, onChange, type, height = '200px' }: LetterheadEditorProps) {
    const [content, setContent] = useState(value || '');
    const [showVariables, setShowVariables] = useState(false);
    const timeoutRef = useRef<NodeJS.Timeout | null>(null);

    // Available variables for replacement
    const variables = [
        { name: '{{ company_name }}', description: 'Company name from settings' },
        { name: '{{ company_address }}', description: 'Company address' },
        { name: '{{ company_email }}', description: 'Company email' },
        { name: '{{ company_phone }}', description: 'Company phone' },
        { name: '{{ company_website }}', description: 'Company website' },
        { name: '{{ page_number }}', description: 'Current page number' },
        { name: '{{ total_pages }}', description: 'Total number of pages' },
        { name: '{{ date }}', description: 'Current date' },
        { name: '{{ year }}', description: 'Current year' },
        { name: '{{ export_title }}', description: 'Title of the export' },
    ];

    useEffect(() => {
        setContent(value || '');
    }, [value]);

    const handleChange = (newContent: string) => {
        setContent(newContent);
        
        // Debounce the onChange call
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
        }
        
        timeoutRef.current = setTimeout(() => {
            onChange(newContent);
        }, 300);
    };

    const insertVariable = (variable: string) => {
        const newContent = content + ' ' + variable + ' ';
        setContent(newContent);
        onChange(newContent);
    };

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <div>
                    <h3 className="text-sm font-medium">
                        {type === 'header' ? 'Header' : 'Footer'} Content
                    </h3>
                    <p className="text-xs text-muted-foreground">
                        Design the {type} that will appear on every page
                    </p>
                </div>
                <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setShowVariables(!showVariables)}
                >
                    <Info className="mr-2 h-4 w-4" />
                    {showVariables ? 'Hide' : 'Show'} Variables
                </Button>
            </div>

            {showVariables && (
                <Card>
                    <CardHeader className="pb-3">
                        <CardTitle className="text-sm">Available Variables</CardTitle>
                        <CardDescription className="text-xs">
                            Click to insert into {type}
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div className="grid grid-cols-2 gap-2">
                            {variables.map((variable) => (
                                <button
                                    key={variable.name}
                                    type="button"
                                    onClick={() => insertVariable(variable.name)}
                                    className="flex flex-col items-start rounded-md border p-2 text-left text-xs hover:bg-accent hover:text-accent-foreground"
                                >
                                    <code className="font-mono font-semibold">{variable.name}</code>
                                    <span className="text-muted-foreground">{variable.description}</span>
                                </button>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            )}

            <div className="rounded-md border">
                <RichTextEditor
                    key={`letterhead-${type}`}
                    initialValue={content}
                    onChange={handleChange}
                    placeholder={`Design your ${type} here... Use variables like {{ company_name }} for dynamic content.`}
                    minHeight={height}
                    enableCodeView
                    enableFullscreen
                    onImageUpload={(file: File) => {
                        // Convert image to base64 for PDF compatibility
                        return new Promise<string>((resolve) => {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                const base64 = e.target?.result as string;
                                resolve(base64);
                            };
                            reader.readAsDataURL(file);
                        });
                    }}
                />
            </div>

            <div className="rounded-md bg-muted p-3 text-xs">
                <p className="font-medium">💡 Tips:</p>
                <ul className="mt-2 space-y-1 text-muted-foreground">
                    <li>• Use inline styles for best PDF rendering (e.g., style="text-align:center")</li>
                    <li>• Keep {type} height reasonable ({type === 'header' ? '100-150px' : '60-100px'})</li>
                    <li>• Variables like {`{{ company_name }}`} will be replaced automatically</li>
                    <li>• You can insert images directly - they'll be embedded as base64 for PDF</li>
                    <li>• Test your design by exporting a PDF</li>
                </ul>
            </div>
        </div>
    );
}
