import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Loader2, Download, Sparkles, Link as LinkIcon } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';
import useTranslation from '@/hooks/useTranslation';

export default function QuickFetchCard({ onFetchSuccess }) {
    const { t } = useTranslation();
    
    // Local State
    const [fetchUrl, setFetchUrl] = useState('');
    const [rewriteWithAi, setRewriteWithAi] = useState(false);
    const [customPrompt, setCustomPrompt] = useState('');
    const [isFetchingUrl, setIsFetchingUrl] = useState(false);

    const handleFetchUrl = async () => {
        if (!fetchUrl) return;
        setIsFetchingUrl(true);

        try {
            const res = await axios.post('/api/user/posts/fetch-url', {
                url: fetchUrl,
                rewrite: rewriteWithAi,
                prompt: rewriteWithAi && customPrompt.trim() !== '' ? customPrompt : null
            });
            
            const fetched = res.data;
            toast.success(fetched.message || t('_article_fetched_success', "Article fetched successfully!"));
            
            // Pass data up to parent component
            onFetchSuccess(fetched);

            // Reset fields
            setFetchUrl('');
            setCustomPrompt('');
            setRewriteWithAi(false);

        } catch (error) {
            toast.error(error.response?.data?.message || t('_fetch_failed', "Failed to fetch article."));
        } finally {
            setIsFetchingUrl(false);
        }
    };

    return (
        <Card className="shadow-sm mb-6 border-primary/20 bg-primary/5 animate-in fade-in slide-in-from-top-4">
            <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg text-primary">
                    <LinkIcon className="w-5 h-5"/> {t('_quick_fetch_article', 'Quick Fetch Article')}
                </CardTitle>
                <CardDescription>
                    {t('_quick_fetch_desc', 'Paste a news URL to automatically extract the headline, content, and cover image.')}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <div className="flex flex-col gap-4">
                    {/* URL Input and Controls */}
                    <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
                        <Input 
                            placeholder={t('_news_url_placeholder', 'https://example.com/news-article')}
                            value={fetchUrl}
                            onChange={e => setFetchUrl(e.target.value)}
                            className="flex-1 bg-background"
                        />
                        <div className="flex items-center gap-4 w-full sm:w-auto justify-between sm:justify-start shrink-0">
                            <div className="flex items-center gap-2">
                                <Switch 
                                    id="ai-rewrite" 
                                    checked={rewriteWithAi} 
                                    onCheckedChange={setRewriteWithAi} 
                                />
                                <Label htmlFor="ai-rewrite" className="cursor-pointer flex items-center gap-1 font-semibold text-purple-600">
                                    <Sparkles className="w-4 h-4" /> {t('_ai_rewrite', 'AI Rewrite')}
                                </Label>
                            </div>
                            <Button type="button" onClick={handleFetchUrl} disabled={isFetchingUrl || !fetchUrl}>
                                {isFetchingUrl ? <Loader2 className="w-4 h-4 mr-2 animate-spin"/> : <Download className="w-4 h-4 mr-2"/>}
                                {t('_fetch', 'Fetch')}
                            </Button>
                        </div>
                    </div>

                    {/* Custom Prompt Box (Only visible if AI Rewrite is ON) */}
                    {rewriteWithAi && (
                        <div className="animate-in fade-in slide-in-from-top-2 pt-2 border-t border-primary/10 mt-2">
                            <Label className="text-purple-700 dark:text-purple-400 mb-2 block">
                                {t('_custom_ai_prompt', 'Custom AI Prompt (Optional)')}
                            </Label>
                            <Textarea 
                                placeholder={t('_custom_prompt_placeholder', 'E.g., Rewrite this in a sarcastic tone, focusing on the main points... Ensure you output the result in HTML <p> tags.')}
                                value={customPrompt}
                                onChange={(e) => setCustomPrompt(e.target.value)}
                                className="h-24 bg-background/50 resize-y font-mono text-sm shadow-inner"
                            />
                            <p className="text-xs text-muted-foreground mt-1">
                                {t('_custom_prompt_helper', "Leave blank to use the system's default professional news rewriting prompt.")}
                            </p>
                        </div>
                    )}
                </div>
            </CardContent>
        </Card>
    );
}