/**
 * Publisher Settings Page
 * Configure automatic approval, publishing limits, and scheduling
 * Uses store-based activeSite instead of URL-based siteId (BUG FIX)
 */
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import PageMeta from '../../components/common/PageMeta';
import PageHeader from '../../components/common/PageHeader';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import IconButton from '../../components/ui/button/IconButton';
import Label from '../../components/form/Label';
import InputField from '../../components/form/input/InputField';
import Switch from '../../components/form/switch/Switch';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchAPI } from '../../services/api';
import { useSiteStore } from '../../store/siteStore';
import { BoltIcon, LayersIcon, CalendarIcon, InfoIcon, CloseIcon, PlusIcon, Loader2Icon } from '../../icons';

export default function PublishSettings() {
  const navigate = useNavigate();
  const toast = useToast();
  const { activeSite } = useSiteStore(); // Use store instead of URL params
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [settings, setSettings] = useState<any>(null);

  // Load publishing settings for active site
  const loadSettings = async () => {
    if (!activeSite) return;
    
    try {
      setLoading(true);
      const response = await fetchAPI(`/v1/integration/sites/${activeSite.id}/publishing-settings/`);
      setSettings(response.data || response);
    } catch (error: any) {
      console.error('Failed to load publishing settings:', error);
      // Set defaults if endpoint fails
      setSettings({
        auto_approval_enabled: true,
        auto_publish_enabled: true,
        daily_publish_limit: 3,
        weekly_publish_limit: 15,
        monthly_publish_limit: 50,
        publish_days: ['mon', 'tue', 'wed', 'thu', 'fri'],
        publish_time_slots: ['09:00', '14:00', '18:00'],
      });
    } finally {
      setLoading(false);
    }
  };

  // Save publishing settings
  const saveSettings = async (newSettings: any) => {
    if (!activeSite) return;
    
    try {
      setSaving(true);
      const response = await fetchAPI(`/v1/integration/sites/${activeSite.id}/publishing-settings/`, {
        method: 'PATCH',
        body: JSON.stringify(newSettings),
      });
      setSettings(response.data || response);
      toast.success('Publishing settings saved successfully');
    } catch (error: any) {
      console.error('Failed to save publishing settings:', error);
      toast.error('Failed to save publishing settings');
    } finally {
      setSaving(false);
    }
  };

  // Load settings on mount and when active site changes
  useEffect(() => {
    if (activeSite) {
      loadSettings();
    }
  }, [activeSite]);

  if (!activeSite) {
    return (
      <div className="p-6">
        <p className="text-gray-600 dark:text-gray-400">Please select a site to configure publishing settings.</p>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-center py-8 text-gray-500">
          <Loader2Icon className="w-8 h-8 animate-spin mx-auto mb-3 text-brand-600" />
          <p>Loading publishing settings...</p>
        </div>
      </div>
    );
  }

  if (!settings) {
    return null;
  }

  return (
    <>
      <PageMeta title="Publishing Settings" description="Configure publishing automation and scheduling" />
      
      <div className="space-y-6">
        <PageHeader
          title="Publishing Settings"
          breadcrumb="Publisher / Settings"
          description="Configure automatic approval, publishing limits, and scheduling"
        />

        {/* 3 Cards in a Row */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          
          {/* Card 1: Automation */}
          <Card className="p-6 border-l-4 border-l-brand-500">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-brand-100 dark:bg-brand-900/30 rounded-lg">
                <BoltIcon className="w-5 h-5 text-brand-600 dark:text-brand-400" />
              </div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Automation</h2>
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
              Configure automatic content approval and publishing to WordPress
            </p>

            <div className="space-y-6">
              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>Auto-Approval</Label>
                  <Switch
                    label=""
                    checked={settings.auto_approval_enabled}
                    onChange={(checked) => {
                      const newSettings = { ...settings, auto_approval_enabled: checked };
                      setSettings(newSettings);
                      saveSettings({ auto_approval_enabled: checked });
                    }}
                  />
                </div>
                <p className="text-xs text-gray-500">
                  Automatically approve content after review
                </p>
              </div>

              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>Auto-Publish</Label>
                  <Switch
                    label=""
                    checked={settings.auto_publish_enabled}
                    onChange={(checked) => {
                      const newSettings = { ...settings, auto_publish_enabled: checked };
                      setSettings(newSettings);
                      saveSettings({ auto_publish_enabled: checked });
                    }}
                  />
                </div>
                <p className="text-xs text-gray-500">
                  Publish approved content to WordPress
                </p>
              </div>
            </div>
          </Card>

          {/* Card 2: Publishing Limits */}
          <Card className="p-6 border-l-4 border-l-success-500">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-success-100 dark:bg-success-900/30 rounded-lg">
                <LayersIcon className="w-5 h-5 text-success-600 dark:text-success-400" />
              </div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Limits</h2>
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
              Set maximum articles to publish per day, week, and month
            </p>

            <div className="space-y-4">
              <div>
                <Label>Daily</Label>
                <InputField
                  type="number"
                  min="1"
                  max="50"
                  value={settings.daily_publish_limit}
                  onChange={(e) => {
                    const value = Math.max(1, Math.min(50, parseInt(e.target.value) || 1));
                    setSettings({ ...settings, daily_publish_limit: value });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">Articles per day</p>
              </div>
              <div>
                <Label>Weekly</Label>
                <InputField
                  type="number"
                  min="1"
                  max="200"
                  value={settings.weekly_publish_limit}
                  onChange={(e) => {
                    const value = Math.max(1, Math.min(200, parseInt(e.target.value) || 1));
                    setSettings({ ...settings, weekly_publish_limit: value });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">Articles per week</p>
              </div>
              <div>
                <Label>Monthly</Label>
                <InputField
                  type="number"
                  min="1"
                  max="500"
                  value={settings.monthly_publish_limit}
                  onChange={(e) => {
                    const value = Math.max(1, Math.min(500, parseInt(e.target.value) || 1));
                    setSettings({ ...settings, monthly_publish_limit: value });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">Articles per month</p>
              </div>
            </div>
          </Card>

          {/* Card 3: Schedule (Days + Time Slots) */}
          <Card className="p-6 border-l-4 border-l-purple-500">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                <CalendarIcon className="w-5 h-5 text-purple-600 dark:text-purple-400" />
              </div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Schedule</h2>
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
              Select which days and times to automatically publish content
            </p>

            <div className="space-y-6">
              <div>
                <Label className="mb-2">Publishing Days</Label>
                <div className="flex flex-wrap gap-2">
                  {[
                    { value: 'mon', label: 'M' },
                    { value: 'tue', label: 'T' },
                    { value: 'wed', label: 'W' },
                    { value: 'thu', label: 'T' },
                    { value: 'fri', label: 'F' },
                    { value: 'sat', label: 'S' },
                    { value: 'sun', label: 'S' },
                  ].map((day) => (
                    <Button
                      key={day.value}
                      variant={(settings.publish_days || []).includes(day.value) ? 'primary' : 'outline'}
                      tone="brand"
                      size="sm"
                      onClick={() => {
                        const currentDays = settings.publish_days || [];
                        const newDays = currentDays.includes(day.value)
                          ? currentDays.filter((d: string) => d !== day.value)
                          : [...currentDays, day.value];
                        setSettings({ ...settings, publish_days: newDays });
                      }}
                      className="w-10 h-10 p-0"
                    >
                      {day.label}
                    </Button>
                  ))}
                </div>
              </div>

              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>Time Slots</Label>
                  {(settings.publish_time_slots || []).length > 0 && (
                    <Button
                      variant="ghost"
                      tone="danger"
                      size="xs"
                      onClick={() => {
                        setSettings({ ...settings, publish_time_slots: [] });
                      }}
                    >
                      Clear All
                    </Button>
                  )}
                </div>
                <p className="text-xs text-gray-500 mb-3">In your local timezone. Content will be published at these times on selected days.</p>
                <div className="space-y-2">
                  {(settings.publish_time_slots || ['09:00', '14:00', '18:00']).length === 0 ? (
                    <div className="text-center py-4 text-gray-500 text-sm border border-dashed border-gray-300 dark:border-gray-700 rounded-md">
                      No time slots configured. Add at least one time slot.
                    </div>
                  ) : (
                    (settings.publish_time_slots || ['09:00', '14:00', '18:00']).map((time: string, index: number) => (
                      <div key={index} className="flex items-center gap-2">
                        <span className="text-xs text-gray-500 w-8">#{index + 1}</span>
                        <InputField
                          type="time"
                          value={time}
                          onChange={(e) => {
                            const newSlots = [...(settings.publish_time_slots || [])];
                            newSlots[index] = e.target.value;
                            setSettings({ ...settings, publish_time_slots: newSlots });
                          }}
                          className="flex-1"
                        />
                        <IconButton
                          icon={<CloseIcon className="w-4 h-4" />}
                          variant="ghost"
                          tone="danger"
                          size="sm"
                          title="Remove this time slot"
                          onClick={() => {
                            const newSlots = (settings.publish_time_slots || []).filter((_: string, i: number) => i !== index);
                            setSettings({ ...settings, publish_time_slots: newSlots });
                          }}
                        />
                      </div>
                    ))
                  )}
                  <Button
                    variant="ghost"
                    tone="brand"
                    size="sm"
                    startIcon={<PlusIcon className="w-4 h-4" />}
                    onClick={() => {
                      const lastSlot = (settings.publish_time_slots || [])[
                        (settings.publish_time_slots || []).length - 1
                      ];
                      // Default new slot to 12:00 or 2 hours after last slot
                      let newTime = '12:00';
                      if (lastSlot) {
                        const [hours, mins] = lastSlot.split(':').map(Number);
                        const newHours = (hours + 2) % 24;
                        newTime = `${String(newHours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
                      }
                      const newSlots = [...(settings.publish_time_slots || []), newTime];
                      setSettings({ ...settings, publish_time_slots: newSlots });
                    }}
                  >
                    Add Time Slot
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* Info Box */}
        <Card className="p-4 bg-brand-50 dark:bg-brand-900/20 border-brand-200 dark:border-brand-800">
          <div className="flex items-start gap-3">
            <InfoIcon className="w-5 h-5 text-brand-600 dark:text-brand-400 mt-0.5 flex-shrink-0" />
            <div className="text-sm text-brand-800 dark:text-brand-200">
              <p className="font-medium mb-1">How Publishing Works</p>
              <ul className="list-disc list-inside space-y-1 text-brand-700 dark:text-brand-300">
                <li>Content moves from Draft → Review → Approved → Published</li>
                <li>Auto-approval moves content from Review to Approved automatically</li>
                <li>Auto-publish sends Approved content to your WordPress site</li>
                <li>You can always manually publish content using the "Publish to Site" button</li>
              </ul>
            </div>
          </div>
        </Card>

        {/* Save Button */}
        <div className="flex justify-end">
          <Button
            variant="primary"
            tone="brand"
            onClick={() => saveSettings(settings)}
            disabled={saving}
          >
            {saving ? 'Saving...' : 'Save Publishing Settings'}
          </Button>
        </div>
      </div>
    </>
  );
}
