/**
 * Publishing Settings Page
 * Phase 6: Site Integration & Multi-Destination Publishing
 */
import React, { useState, useEffect } from 'react';
import PageMeta from '../../components/common/PageMeta';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import Checkbox from '../../components/form/input/Checkbox';
import Label from '../../components/form/Label';
import Input from '../../components/form/input/InputField';
import Select from '../../components/form/SelectDropdown';
import PublishingRules, { PublishingRule } from '../../components/publishing/PublishingRules';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchAPI } from '../../services/api';

export default function Publishing() {
  const toast = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [defaultDestinations, setDefaultDestinations] = useState<string[]>(['sites']);
  const [autoPublishEnabled, setAutoPublishEnabled] = useState(false);
  const [autoSyncEnabled, setAutoSyncEnabled] = useState(false);
  const [syncInterval, setSyncInterval] = useState<number>(60); // Default 60 minutes
  const [syncIntervalUnit, setSyncIntervalUnit] = useState<'minutes' | 'hours'>('minutes');
  const [publishingRules, setPublishingRules] = useState<PublishingRule[]>([]);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      setLoading(true);
      // TODO: Load from backend API when endpoint is available
      // For now, use defaults
      setDefaultDestinations(['sites']);
      setAutoPublishEnabled(false);
      setAutoSyncEnabled(false);
      setSyncInterval(60);
      setSyncIntervalUnit('minutes');
      setPublishingRules([]);
    } catch (error: any) {
      toast.error(`Failed to load settings: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      // TODO: Save to backend API when endpoint is available
      toast.success('Publishing settings saved successfully');
    } catch (error: any) {
      toast.error(`Failed to save settings: ${error.message}`);
    } finally {
      setSaving(false);
    }
  };

  const handleToggleDestination = (destination: string) => {
    setDefaultDestinations((prev) =>
      prev.includes(destination)
        ? prev.filter((d) => d !== destination)
        : [...prev, destination]
    );
  };

  const DESTINATIONS = [
    { value: 'sites', label: 'IGNY8 Sites' },
    { value: 'wordpress', label: 'WordPress' },
    { value: 'shopify', label: 'Shopify' },
  ];

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Publishing Settings" />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">Loading...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <PageMeta title="Publishing Settings - IGNY8" />
      
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
          Publishing Settings
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Configure default publishing destinations and rules
        </p>
      </div>

      <div className="space-y-6">
        {/* Default Destinations */}
        <Card className="p-6">
          <div className="space-y-4">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                Default Publishing Destinations
              </h2>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Select default platforms where content will be published
              </p>
            </div>

            <div className="space-y-2">
              {DESTINATIONS.map((dest) => (
                <div key={dest.value} className="flex items-center gap-3">
                  <Checkbox
                    checked={defaultDestinations.includes(dest.value)}
                    onChange={() => handleToggleDestination(dest.value)}
                    label={dest.label}
                  />
                </div>
              ))}
            </div>
          </div>
        </Card>

        {/* Auto-Publish Settings */}
        <Card className="p-6">
          <div className="space-y-4">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                Auto-Publish Settings
              </h2>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Automatically publish content when it's ready
              </p>
            </div>

            <div className="flex items-center gap-3">
              <Checkbox
                checked={autoPublishEnabled}
                onChange={(e) => setAutoPublishEnabled(e.target.checked)}
                label="Enable auto-publish"
              />
            </div>

            {autoPublishEnabled && (
              <div className="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                <p className="text-sm text-blue-800 dark:text-blue-200">
                  When enabled, content will be automatically published to selected destinations
                  when generation is complete.
                </p>
              </div>
            )}
          </div>
        </Card>

        {/* Auto-Sync Settings */}
        <Card className="p-6">
          <div className="space-y-4">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                Auto-Sync Settings
              </h2>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Configure automatic content synchronization with publishing platforms
              </p>
            </div>

            <div className="flex items-center gap-3">
              <Checkbox
                checked={autoSyncEnabled}
                onChange={(e) => setAutoSyncEnabled(e.target.checked)}
                label="Enable auto-sync"
              />
            </div>

            {autoSyncEnabled && (
              <div className="mt-4 space-y-4">
                <div>
                  <Label>Sync Interval</Label>
                  <div className="flex gap-3 items-center mt-2">
                    <div className="w-32">
                      <Input
                        type="number"
                        min="1"
                        max={syncIntervalUnit === 'minutes' ? 1440 : 24}
                        value={syncInterval}
                        onChange={(e) => setSyncInterval(parseInt(e.target.value) || 1)}
                        placeholder="60"
                      />
                    </div>
                    <div className="w-32">
                      <Select
                        value={syncIntervalUnit}
                        onChange={(e) => setSyncIntervalUnit(e.target.value as 'minutes' | 'hours')}
                      >
                        <option value="minutes">Minutes</option>
                        <option value="hours">Hours</option>
                      </Select>
                    </div>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    How often the system should check for and publish ready content
                  </p>
                </div>

                <div className="p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
                  <p className="text-sm text-amber-800 dark:text-amber-200">
                    <strong>Note:</strong> Content will be automatically published every{' '}
                    {syncInterval} {syncIntervalUnit} if it has status "review" and all images are generated.
                  </p>
                </div>
              </div>
            )}
          </div>
        </Card>

        {/* Publishing Rules */}
        <Card className="p-6">
          <PublishingRules rules={publishingRules} onChange={setPublishingRules} />
        </Card>

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

