import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    Loader2, Globe, Terminal, Copy, RefreshCw, Play, Rocket, Clock, 
    CalendarClock, Save, Timer, Info, CheckCircle 
} from 'lucide-react';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Switch } from "@/Components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Skeleton } from '@/Components/ui/skeleton';
import ConfirmModal from '@/Components/ConfirmModal';

export default function Scheduler() {
    // --- State ---
    const [token, setToken] = useState('');
    const [loading, setLoading] = useState(true);
    const [isRegenerating, setIsRegenerating] = useState(false);
    const [isCrawling, setIsCrawling] = useState(false);
    const [isSavingConfig, setIsSavingConfig] = useState(false);
    const [isConfirmOpen, setIsConfirmOpen] = useState(false);

    // Config State
    const [config, setConfig] = useState({
        rss_schedule_enabled: true,
        rss_schedule_frequency: 60,
        rss_last_scheduled_run: null,
        rss_next_scheduled_run: null
    });

    // --- Data Fetching ---
    useEffect(() => {
        fetchSchedulerData();
    }, []);

    const fetchSchedulerData = async () => {
        setLoading(true);
        try {
            const res = await axios.get('/api/admin/system/scheduler');
            setToken(res.data.token);
            setConfig(res.data.config);
        } catch (error) {
            toast.error("Failed to load scheduler information.");
        } finally {
            setLoading(false);
        }
    };

    // --- Handlers ---
    const handleSaveConfig = async () => {
        setIsSavingConfig(true);
        try {
            await axios.post('/api/admin/system/scheduler/settings', config);
            toast.success("Schedule settings updated.");
            await fetchSchedulerData(); // Refresh UI to calculate new 'Next Run' time
        } catch (error) {
            toast.error("Failed to update settings.");
        } finally {
            setIsSavingConfig(false);
        }
    };

    const handleCopy = (text) => {
        navigator.clipboard.writeText(text);
        toast.success("Copied to clipboard!");
    };

    const handleRegenerate = async () => {
        setIsRegenerating(true);
        try {
            const res = await axios.post('/api/admin/system/scheduler/regenerate-token');
            setToken(res.data.token);
            toast.success("Token has been regenerated.");
        } catch (error) {
            toast.error("Failed to regenerate token.");
        } finally {
            setIsRegenerating(false);
            setIsConfirmOpen(false);
        }
    };

    const handleInstantCrawl = async () => {
        setIsCrawling(true);
        toast.info("Dispatching crawler jobs...");
        
        try {
            const res = await axios.post('/api/admin/system/scheduler/run-crawl');
            toast.success(res.data.message || "Crawl completed successfully.");
            await fetchSchedulerData(); // Update Last Run time
        } catch (error) {
            toast.error("Crawl Failed", {
                description: error.response?.data?.message || "Server error occurred."
            });
        } finally {
            setIsCrawling(false);
        }
    };

    const formatTime = (timestamp) => {
        if (!timestamp || timestamp === 0) return 'Never';
        const date = new Date(timestamp * 1000);
        return date.toLocaleString(undefined, {
            weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
        });
    };

    // Static Web Cron URL
    const webCronUrl = `${window.location.origin}/run-scheduler/${token}`;
    
    // Explicit Placeholder Paths for Server CLI Commands
    const placeholderPath = "/path/to/your/project";
    const standardCronCommand = `* * * * * /usr/bin/php ${placeholderPath}/artisan schedule:run >> /dev/null 2>&1`;
    const cdCronCommand = `* * * * * cd ${placeholderPath} && php artisan schedule:run >> /dev/null 2>&1`;

    return (
        <AdminLayout>
            <Head title="Crawler & Scheduler" />
            <SettingsLayout>

                <ConfirmModal
                    open={isConfirmOpen}
                    onOpenChange={setIsConfirmOpen}
                    onConfirm={handleRegenerate}
                    title="Regenerate Web Cron Token?"
                    description="This will invalidate the current URL. You must update your external cron job service with the new URL."
                    confirmText="Yes, Regenerate"
                    variant="destructive"
                />

                <div className="space-y-6">
                    
                    {/* --- RECOMMENDATION ALERT --- */}
                    <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-4 rounded-lg flex gap-3 shadow-sm">
                        <Info className="w-5 h-5 text-blue-600 dark:text-blue-400 shrink-0 mt-0.5" />
                        <div className="text-sm text-blue-800 dark:text-blue-200">
                            <p className="font-bold mb-1">Recommended Setup: Web Cron</p>
                            <p>For most users on shared hosting (cPanel/DirectAdmin), we highly recommend using <strong>Web Cron</strong>. It is easier to set up and very reliable. Simply use the URL provided below with a free service like <a href="https://cron-job.org" target="_blank" rel="noreferrer" className="underline font-bold">cron-job.org</a>.</p>
                        </div>
                    </div>

                    {/* --- 1. DYNAMIC SCHEDULER CONFIG --- */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2">
                                <CalendarClock className="w-5 h-5 text-purple-500" /> Auto-Crawl Schedule
                            </CardTitle>
                            <CardDescription>
                                Set the frequency for automatic background checks.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-6">
                            <div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm bg-card">
                                <div className="space-y-0.5">
                                    <Label className="text-base">Enable Automatic Crawling</Label>
                                    <div className="text-sm">
                                        Status: {config.rss_schedule_enabled 
                                            ? <span className="text-green-600 font-bold ml-1">Active</span> 
                                            : <span className="text-red-500 font-bold ml-1">Disabled</span>}
                                    </div>
                                    <p className="text-xs text-muted-foreground mt-1">
                                        If disabled, feeds will only update when you click "Run Now".
                                    </p>
                                </div>
                                <Switch 
                                    checked={config.rss_schedule_enabled}
                                    onCheckedChange={(c) => setConfig({ ...config, rss_schedule_enabled: c })}
                                />
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-2">
                                    <Label>Check Frequency</Label>
                                    <Select 
                                        value={String(config.rss_schedule_frequency)} 
                                        onValueChange={(val) => setConfig({ ...config, rss_schedule_frequency: parseInt(val) })}
                                        disabled={!config.rss_schedule_enabled}
                                    >
                                        <SelectTrigger><SelectValue placeholder="Select frequency" /></SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="5">Every 5 Minutes</SelectItem>
                                            <SelectItem value="15">Every 15 Minutes</SelectItem>
                                            <SelectItem value="30">Every 30 Minutes</SelectItem>
                                            <SelectItem value="60">Every Hour</SelectItem>
                                            <SelectItem value="120">Every 2 Hours</SelectItem>
                                            <SelectItem value="360">Every 6 Hours</SelectItem>
                                            <SelectItem value="720">Every 12 Hours</SelectItem>
                                            <SelectItem value="1440">Once a Day</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>

                                <div className="space-y-3">
                                    <div className="flex justify-between items-center text-sm">
                                        <span className="text-muted-foreground flex items-center gap-2"><Clock className="w-4 h-4" /> Last Run:</span>
                                        <span className="font-medium font-mono text-xs sm:text-sm">{formatTime(config.rss_last_scheduled_run)}</span>
                                    </div>
                                    <div className="flex justify-between items-center text-sm p-2 rounded-md bg-primary/5 border border-primary/10">
                                        <span className="text-primary flex items-center gap-2 font-semibold"><Timer className="w-4 h-4" /> Next Run:</span>
                                        <span className="font-bold text-primary font-mono text-xs sm:text-sm">{config.rss_schedule_enabled ? formatTime(config.rss_next_scheduled_run) : "Paused"}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="flex justify-end pt-2 border-t">
                                <Button onClick={handleSaveConfig} disabled={isSavingConfig || loading}>
                                    {isSavingConfig ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
                                    Save Schedule
                                </Button>
                            </div>
                        </CardContent>
                    </Card>

                    {/* --- 2. INSTANT CRAWL --- */}
                    <Card className="border-primary/20 bg-primary/5">
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2 text-primary">
                                <Rocket className="w-5 h-5" /> Instant Job Dispatch
                            </CardTitle>
                            <CardDescription>
                                Bypass the timer and process all feeds manually right now.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <Button size="lg" onClick={handleInstantCrawl} disabled={isCrawling || loading} className="w-full sm:w-auto font-bold shadow-md">
                                {isCrawling ? <><Loader2 className="mr-2 h-5 w-5 animate-spin" />Processing...</> : <><Play className="mr-2 h-5 w-5" />Run Global Crawl Now</>}
                            </Button>
                        </CardContent>
                    </Card>

                    {/* --- 3. TECHNICAL SETUP GUIDELINES --- */}
                    <div className="grid grid-cols-1 gap-6">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2"><Globe className="w-5 h-5 text-blue-500" /> Web Cron Setup</CardTitle>
                                <CardDescription>Use this URL with an external service to trigger the scheduler.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="flex gap-2">
                                    {loading ? <Skeleton className="h-9 flex-1" /> : <Input value={webCronUrl} readOnly className="bg-muted" />}
                                    <Button variant="outline" size="icon" onClick={() => handleCopy(webCronUrl)}><Copy className="w-4 h-4" /></Button>
                                </div>
                                <div className="flex justify-end">
                                    <Button variant="ghost" size="sm" className="text-red-500 h-8 px-2" onClick={() => setIsConfirmOpen(true)} disabled={isRegenerating}>
                                        <RefreshCw className="w-3 h-3 mr-1"/> Reset Token
                                    </Button>
                                </div>
                            </CardContent>
                        </Card>

                        {/* --- NEW SERVER CLI SETUP GUIDE --- */}
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2 text-green-600"><Terminal className="w-5 h-5" /> Server CLI Setup (VPS / cPanel)</CardTitle>
                                <CardDescription>If you have SSH access or a cPanel Cron Jobs section, use one of the methods below.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-6">
                                
                                <div className="space-y-3">
                                    <Label className="font-bold">Option A: Standard Cron (Recommended for cPanel)</Label>
                                    <p className="text-xs text-muted-foreground">
                                        Add this exact line to your server's crontab or cPanel Cron Jobs panel to run every minute.
                                        <br/><strong className="text-red-500">Replace <code>/path/to/your/project</code> with your actual server path (e.g. <code>/home/user/public_html</code>).</strong>
                                    </p>
                                    <div className="flex gap-2 mt-1">
                                        <Input value={standardCronCommand} readOnly className="bg-muted font-mono text-[11px] h-10" />
                                        <Button variant="outline" size="icon" className="h-10 w-10 shrink-0" onClick={() => handleCopy(standardCronCommand)}>
                                            <Copy className="w-4 h-4" />
                                        </Button>
                                    </div>
                                    <p className="text-[10px] text-muted-foreground italic mt-1">Note: If your PHP binary is not at <code>/usr/bin/php</code>, adjust the path accordingly.</p>
                                </div>

                                <div className="space-y-3 pt-4 border-t">
                                    <Label className="font-bold">Option B: CD Cron (Alternative)</Label>
                                    <p className="text-xs text-muted-foreground">
                                        If Option A fails, try navigating to the directory first. 
                                        <br/><strong className="text-red-500">Replace <code>/path/to/your/project</code> with your actual server path.</strong>
                                    </p>
                                    <div className="flex gap-2 mt-1">
                                        <Input value={cdCronCommand} readOnly className="bg-muted font-mono text-[11px] h-10" />
                                        <Button variant="outline" size="icon" className="h-10 w-10 shrink-0" onClick={() => handleCopy(cdCronCommand)}>
                                            <Copy className="w-4 h-4" />
                                        </Button>
                                    </div>
                                </div>

                                <div className="space-y-3 pt-4 border-t">
                                    <Label className="font-bold">Option C: aaPanel / Supervisor Background Worker</Label>
                                    <p className="text-xs text-muted-foreground">If you prefer running a continuous background worker using Supervisor (Process Manager):</p>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-2">
                                        <div className="p-3 bg-muted/30 border rounded-md text-xs font-mono space-y-1">
                                            <p><strong>Name:</strong> my-app-scheduler</p>
                                            <p><strong>Run User:</strong> www <em>(or your specific user)</em></p>
                                            <p><strong>Run Dir:</strong> /path/to/your/project</p>
                                            <p><strong>Command:</strong> <span className="text-green-600 dark:text-green-400">php artisan schedule:work</span></p>
                                        </div>
                                    </div>
                                </div>
                                
                                <div className="p-4 bg-amber-50 dark:bg-amber-900/10 border border-amber-200 rounded-lg text-sm text-amber-800 dark:text-amber-200">
                                    <p className="font-bold flex items-center gap-1 text-foreground mb-2"><CheckCircle className="w-4 h-4 text-green-500"/> How this works:</p>
                                    <ul className="list-disc pl-5 space-y-1 text-xs">
                                        <li>The Cron runs every minute to keep the system alive in the background (even if terminal is closed).</li>
                                        <li>It checks your <strong>Check Frequency</strong> setting (e.g., 5 mins) before executing.</li>
                                        <li>If the time has arrived, it will import news and process the queue automatically.</li>
                                        <li>Run <code>php artisan schedule:list</code> in your terminal to verify the task is registered.</li>
                                    </ul>
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </SettingsLayout>
        </AdminLayout>
    );
}