"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/Components/UI/Card"
import { Button } from "@/Components/UI/Button"
import { Badge } from "@/Components/UI/Badge"
import { Switch } from "@/Components/UI/Switch"
import { 
  Clock, 
  Server, 
  CheckCircle, 
  XCircle, 
  AlertTriangle,
  Copy,
  RefreshCw,
  Calendar,
  Zap,
  Terminal,
  ExternalLink,
  Play,
  Pause,
  RotateCcw
} from "lucide-react"
import { motion } from "framer-motion"
import useTranslate from "@/hooks/useTranslate"
import { router } from "@inertiajs/react"
import toast from "react-hot-toast"

export default function AutomationSettings({ cronJobs = [], systemStatus = {}, cronUrls = [] }) {
  const [expandedJob, setExpandedJob] = useState(null)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const t = useTranslate()

  // Default cron jobs configuration
  const defaultCronJobs = Array.isArray(cronJobs) && cronJobs.length > 0 ? cronJobs : [
    {
      id: 'post_scheduler',
      name: t('Post Scheduler'),
      description: t('Automatically publishes scheduled social media posts'),
      frequency: '* * * * *', // Every minute
      command: 'posts-schedule',
      endpoint: '/user/cron/post-scheduler',
      status: 'active',
      last_run: '2 minutes ago',
      next_run: 'In 58 seconds',
      success_rate: 98.5,
      total_runs: 1247,
      failures: 19,
      category: 'content'
    },
    {
      id: 'analytics_sync',
      name: t('Analytics Sync'),
      description: t('Syncs analytics data from social platforms'),
      frequency: '0 */6 * * *', // Every 6 hours
      command: 'analytics-sync',
      endpoint: '/user/cron/analytics-sync',
      status: 'active',
      last_run: '3 hours ago',
      next_run: 'In 3 hours',
      success_rate: 95.2,
      total_runs: 456,
      failures: 22,
      category: 'analytics'
    },
    {
      id: 'account_refresh',
      name: t('Account Token Refresh'),
      description: t('Refreshes social media account access tokens'),
      frequency: '0 2 * * *', // Daily at 2 AM
      command: 'accounts-refresh-tokens',
      endpoint: '/user/cron/refresh-tokens',
      status: 'active',
      last_run: '8 hours ago',
      next_run: 'In 16 hours',
      success_rate: 99.1,
      total_runs: 89,
      failures: 1,
      category: 'security'
    },
    {
      id: 'cleanup',
      name: t('System Cleanup'),
      description: t('Cleans up temporary files and old logs'),
      frequency: '0 3 * * 0', // Weekly on Sunday at 3 AM
      command: 'system-cleanup',
      endpoint: '/user/cron/system-cleanup',
      status: 'active',
      last_run: '2 days ago',
      next_run: 'In 5 days',
      success_rate: 100,
      total_runs: 12,
      failures: 0,
      category: 'maintenance'
    },
    {
      id: 'backup',
      name: t('Automated Backup'),
      description: t('Creates automated backups of important data'),
      frequency: '0 1 * * *', // Daily at 1 AM
      command: 'backup-run',
      endpoint: '/user/cron/auto-backup',
      status: 'active',
      last_run: '9 hours ago',
      next_run: 'In 15 hours',
      success_rate: 97.8,
      total_runs: 67,
      failures: 2,
      category: 'backup'
    }
  ]

  const getCategoryColor = (category) => {
    const colors = {
      content: 'from-blue-500 to-cyan-500',
      analytics: 'from-purple-500 to-pink-500',
      security: 'from-green-500 to-emerald-500',
      maintenance: 'from-orange-500 to-red-500',
      backup: 'from-indigo-500 to-purple-500'
    }
    return colors[category] || 'from-gray-500 to-gray-600'
  }

  const getCategoryIcon = (category) => {
    const icons = {
      content: Calendar,
      analytics: RefreshCw,
      security: CheckCircle,
      maintenance: Server,
      backup: RotateCcw
    }
    const IconComponent = icons[category] || Clock
    return <IconComponent className="w-4 h-4" />
  }

  const getStatusBadge = (status, successRate) => {
    if (status === 'inactive') {
      return <Badge variant="secondary" className="flex items-center gap-1"><Pause className="w-3 h-3" /> {t('Paused')}</Badge>
    }
    if (successRate >= 98) {
      return <Badge className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300 flex items-center gap-1"><CheckCircle className="w-3 h-3" /> {t('Healthy')}</Badge>
    }
    if (successRate >= 90) {
      return <Badge className="bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300 flex items-center gap-1"><AlertTriangle className="w-3 h-3" /> {t('Warning')}</Badge>
    }
    return <Badge className="bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300 flex items-center gap-1"><XCircle className="w-3 h-3" /> {t('Error')}</Badge>
  }

  const copyToClipboard = async (text) => {
    try {
      // Modern clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text)
        toast.success(t('Copied to clipboard'))
      } else {
        // Fallback for older browsers or insecure contexts
        const textArea = document.createElement('textarea')
        textArea.value = text
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        
        try {
          const result = document.execCommand('copy')
          if (result) {
            toast.success(t('Copied to clipboard'))
          } else {
            throw new Error('Copy command failed')
          }
        } catch (err) {
          console.error('Fallback copy failed:', err)
          toast.error(t('Failed to copy to clipboard'))
        } finally {
          document.body.removeChild(textArea)
        }
      }
    } catch (err) {
      console.error('Copy to clipboard failed:', err)
      toast.error(t('Failed to copy to clipboard. Please copy manually.'))
    }
  }

  const handleRefreshStatus = async () => {
    setIsRefreshing(true)
    try {
      await router.reload({ only: ['cronJobs', 'systemStatus'] })
      toast.success(t('Status refreshed successfully'))
    } catch (error) {
      toast.error(t('Failed to refresh status'))
    } finally {
      setIsRefreshing(false)
    }
  }

  const toggleCronJob = async (jobId, currentStatus) => {
    try {
      await router.post(route('user.cron.toggle'), {
        job_id: jobId,
        status: currentStatus === 'active' ? 'inactive' : 'active'
      })
      toast.success(t('Cron job status updated'))
    } catch (error) {
      toast.error(t('Failed to update cron job status'))
    }
  }

  const runCronJobNow = async (jobId) => {
    try {
      await router.post(route('user.cron.run-now'), { job_id: jobId })
      toast.success(t('Cron job executed successfully'))
    } catch (error) {
      toast.error(t('Failed to execute cron job'))
    }
  }

  return (
    <div className="space-y-6">
      {/* System Status Overview */}
      <Card className="border-0 shadow-lg bg-gradient-to-br from-white to-blue-50 dark:from-zinc-900 dark:to-blue-950">
  <CardHeader className="pb-4">
    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      {/* Left side */}
      <div className="flex items-center space-x-3">
        <div>
          <CardTitle className="text-lg sm:text-xl">{t("System Status")}</CardTitle>
          <p className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">
            {t("Real-time automation monitoring")}
          </p>
        </div>
      </div>

      {/* Button */}
      <Button
        variant="outline"
        size="sm"
        onClick={handleRefreshStatus}
        disabled={isRefreshing}
        className="flex items-center gap-2 w-full sm:w-auto justify-center"
      >
        <RefreshCw className={`w-4 h-4 ${isRefreshing ? "animate-spin" : ""}`} />
        {t("Refresh")}
      </Button>
    </div>
  </CardHeader>

  <CardContent>
    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
      {/* Status Item 1 */}
      <div className="text-start">
        <div className="flex items-center justify-start mb-2">
          <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse mr-2"></div>
          <span className="text-sm font-medium text-green-600 dark:text-green-400">
            {t("All systems operational")}
          </span>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400">
          {t("All cron jobs running normally")}
        </p>
      </div>

      {/* Status Item 2 */}
      <div className="text-start">
        <div className="flex items-center justify-start mb-2">
          <Clock className="w-4 h-4 text-blue-500 mr-2" />
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            {systemStatus?.last_cron_run || t("2 minutes ago")}
          </span>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400">{t("Last cron job run")}</p>
      </div>

      {/* Status Item 3 */}
      <div className="text-start">
        <div className="flex items-center justify-start mb-2">
          <CheckCircle className="w-4 h-4 text-green-500 mr-2" />
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            {systemStatus?.success_rate || "98.7%"}
          </span>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400">{t("Overall success rate")}</p>
      </div>
    </div>
  </CardContent>
</Card>


      {/* Cron Jobs List */}
      <Card className="border-0 shadow-none">
  <CardHeader className="p-0">
    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
      <div>
        <CardTitle className="flex items-center gap-2 text-base sm:text-lg">
          <Zap className="w-5 h-5 text-yellow-500" />
          {t("Automation Jobs")}
        </CardTitle>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
          {t("Manage and monitor your automated tasks")}
        </p>
      </div>
      <Badge variant="outline" className="text-xs self-start sm:self-auto">
        {defaultCronJobs.filter((job) => job.status === "active").length} {t("Active")}
      </Badge>
    </div>
  </CardHeader>

  <CardContent className="space-y-4 px-0 pt-4">
    {defaultCronJobs.map((job, index) => (
      <motion.div
        key={job.id}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: index * 0.1 }}
        className="border border-gray-200 dark:border-zinc-800 rounded-lg p-4 hover:shadow-md transition-all duration-200"
      >
        {/* Top Row */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
          <div className="flex items-center space-x-3">
            <div
              className={`w-8 h-8 bg-gradient-to-br ${getCategoryColor(
                job.category
              )} rounded-lg flex items-center justify-center text-white`}
            >
              {getCategoryIcon(job.category)}
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">{job.name}</h3>
              <p className="text-xs text-gray-500 dark:text-gray-400">{job.description}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {getStatusBadge(job.status, job.success_rate)}
            <Switch
              checked={job.status === "active"}
              onCheckedChange={() => toggleCronJob(job.id, job.status)}
              size="sm"
            />
          </div>
        </div>

        {/* Info Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-xs">
          <div>
            <span className="text-gray-500 dark:text-gray-400">{t("Last Run")}</span>
            <p className="font-medium text-gray-900 dark:text-white">{job.last_run}</p>
          </div>
          <div>
            <span className="text-gray-500 dark:text-gray-400">{t("Next Run")}</span>
            <p className="font-medium text-gray-900 dark:text-white">{job.next_run}</p>
          </div>
          <div>
            <span className="text-gray-500 dark:text-gray-400">{t("Success Rate")}</span>
            <p className="font-medium text-gray-900 dark:text-white">{job.success_rate}%</p>
          </div>
          <div>
            <span className="text-gray-500 dark:text-gray-400">{t("Total Runs")}</span>
            <p className="font-medium text-gray-900 dark:text-white">
              {job.total_runs.toLocaleString()}
            </p>
          </div>
        </div>

        {/* Footer Row */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mt-4 pt-3 border-t border-gray-100 dark:border-zinc-700">
          <div className="flex flex-wrap items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
            <span className="flex items-center">
              <Terminal className="w-3 h-3 mr-1" />
              {job.frequency}
            </span>
            {job.failures > 0 && (
              <span className="flex items-center text-red-500">
                <XCircle className="w-3 h-3 mr-1" />
                {job.failures} {t("failures")}
              </span>
            )}
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() =>
                copyToClipboard(job.url || `${window.location.origin}/cron/${job.command}`)
              }
              className="text-xs px-2 py-1 h-6"
            >
              <Copy className="w-3 h-3 mr-1" />
              {t("Copy URL")}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => runCronJobNow(job.id)}
              className="text-xs px-2 py-1 h-6"
              disabled={job.status === "inactive"}
            >
              <Play className="w-3 h-3 mr-1" />
              {t("Run Now")}
            </Button>
          </div>
        </div>
      </motion.div>
    ))}
  </CardContent>
</Card>


      {/* Server Setup Guide */}
      <Card className="border-0 shadow-none">
  <CardHeader className="p-0">
    <CardTitle className="flex items-center gap-2 text-base sm:text-lg">
      <Server className="w-5 h-5 text-blue-500" />
      {t('Server Setup Guide')}
    </CardTitle>
    <p className="text-sm text-gray-600 dark:text-gray-400">
      {t('Configure cron jobs on your server for automated task execution')}
    </p>
  </CardHeader>

  <CardContent className="space-y-6 pt-4 px-0">
    {/* cPanel/Shared Hosting */}
    <div className="border border-gray-200 dark:border-zinc-800 rounded-lg p-4">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 gap-2">
        <h3 className="font-medium text-gray-900 dark:text-white flex items-center gap-2 text-sm sm:text-base">
          <Server className="w-4 h-4" />
          {t('cPanel / Shared Hosting')}
        </h3>
      </div>

      <div className="space-y-4 text-sm">
        <p className="text-gray-600 dark:text-gray-400">
          {t('For shared hosting providers like cPanel, GoDaddy, Bluehost, etc. Choose either method:')}
        </p>

        {/* Method 1 */}
        <div className="space-y-2">
          <h4 className="font-medium text-gray-900 dark:text-white text-sm sm:text-base">
            {t('Method 1: Artisan Command (Traditional)')}
          </h4>
          <div className="bg-gray-50 dark:bg-zinc-800 rounded-lg p-3 font-mono text-xs overflow-x-auto">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-2 gap-2">
              <span className="text-gray-600 dark:text-gray-400">
                {t('Add this cron job (every minute):')}
              </span>
              <Button
                variant="ghost"
                size="sm"
                onClick={() =>
                  copyToClipboard('* * * * * /usr/bin/php /path/to/your/website/artisan schedule:run >> /dev/null 2>&1')
                }
                className="p-1 self-start sm:self-auto"
              >
                <Copy className="w-3 h-3" />
              </Button>
            </div>
            <code className="text-blue-600 dark:text-blue-400 block">
              * * * * * /usr/bin/php /path/to/your/website/artisan schedule:run {'>>'} /dev/null 2&gt;&amp;1
            </code>
          </div>
        </div>

        {/* Method 2 */}
        <div className="space-y-2">
          <h4 className="font-medium text-gray-900 dark:text-white text-sm sm:text-base">
            {t('Method 2: URL/cURL (Recommended for Shared Hosting)')}
          </h4>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {t('Setup individual cron jobs for each task using URLs. This works even if Artisan commands are restricted.')}
          </p>
          <div className="space-y-2">
            {defaultCronJobs.map((job) => (
              <div key={job.id} className="bg-gray-50 dark:bg-zinc-800 rounded-lg p-3 font-mono text-xs overflow-x-auto">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-2 gap-2">
                  <span className="text-xs font-medium text-gray-700 dark:text-gray-300">{job.name}</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() =>
                      copyToClipboard(`${job.frequency || '* * * * *'} curl -s "${window.location.origin}/cron/${job.command}" > /dev/null 2>&1`)
                    }
                    className="p-1 self-start sm:self-auto"
                  >
                    <Copy className="w-3 h-3" />
                  </Button>
                </div>
                <code className="text-xs text-blue-600 dark:text-blue-400 block break-all">
                  {job.frequency || '* * * * *'} curl -s "{window.location.origin}/cron/{job.command}" {'>>'} /dev/null 2&gt;&amp;1
                </code>
                <div className="mt-1 text-xs text-gray-500 dark:text-gray-400 break-all">
                  URL: {window.location.origin}/cron/{job.command}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="space-y-2">
          <p className="font-medium text-gray-900 dark:text-white">{t('General Steps:')}</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 dark:text-gray-400 text-sm">
            <li>{t('Log in to your cPanel or hosting control panel')}</li>
            <li>{t('Navigate to "Cron Jobs" or "Scheduled Tasks"')}</li>
            <li>{t('Choose Method 1 (Artisan) or Method 2 (URLs) above')}</li>
            <li>{t('For Method 1: Replace "/path/to/your/website" with your actual site path')}</li>
            <li>{t('For Method 2: Set up separate cron jobs for each URL with their frequencies')}</li>
            <li>{t('Save the cron job(s)')}</li>
          </ol>
        </div>
      </div>
    </div>

    {/* VPS/Dedicated Server */}
    <div className="border border-gray-200 dark:border-zinc-800 rounded-lg p-4">
      <h3 className="font-medium text-gray-900 dark:text-white flex items-center gap-2 mb-3 text-sm sm:text-base">
        <Terminal className="w-4 h-4" />
        {t('VPS / Dedicated Server')}
      </h3>
      <div className="space-y-3 text-sm">
        <p className="text-gray-600 dark:text-gray-400">
          {t('For VPS, dedicated servers, or when you have SSH access.')}
        </p>
        <div className="bg-gray-50 dark:bg-zinc-800 rounded-lg p-3 font-mono text-xs space-y-2 overflow-x-auto">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
            <span className="text-gray-600 dark:text-gray-400">{t('1. Edit crontab:')}</span>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => copyToClipboard('crontab -e')}
              className="p-1 self-start sm:self-auto"
            >
              <Copy className="w-3 h-3" />
            </Button>
          </div>
          <code className="text-green-600 dark:text-green-400 block">crontab -e</code>

          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
            <span className="text-gray-600 dark:text-gray-400">{t('2. Add this line:')}</span>
            <Button
              variant="ghost"
              size="sm"
              onClick={() =>
                copyToClipboard('* * * * * cd /path/to/your/project && php artisan schedule:run >> /dev/null 2>&1')
              }
              className="p-1 self-start sm:self-auto"
            >
              <Copy className="w-3 h-3" />
            </Button>
          </div>
          <code className="text-blue-600 dark:text-blue-400 block">
            * * * * * cd /path/to/your/project &amp;&amp; php artisan schedule:run {'>>'} /dev/null 2&gt;&amp;1
          </code>
        </div>
      </div>
    </div>
  </CardContent>
</Card>

    </div>
  )
}