import { useState, useEffect } from 'react';
import { SettingsSaveBar } from './SettingsSaveBar';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Label } from './ui/label';
import { Switch } from './ui/switch';
import { Skeleton } from './ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from './ui/accordion';
import { Wrench, Play, Monitor } from 'lucide-react';
import { useSettingsForm } from '../hooks/useSettingsForm';
import { cn } from '../lib/utils';
import { toast } from '../lib/toast';
import { __ } from '../lib/i18n';

interface SystemInfo {
  action_scheduler_version: string;
  plugin_version: string;
  wordpress_version: string;
  php_version: string;
}

export default function Settings() {
  const {
    settings,
    updateSetting,
    isDirty,
    changedFields,
    save,
    discard,
    isSaving,
    isLoading,
    error,
  } = useSettingsForm();

  const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
  const [systemInfoLoading, setSystemInfoLoading] = useState(true);

  useEffect(() => {
    fetch(`${window.sequensyAPI.root}/system/info`, {
      headers: { 'X-WP-Nonce': window.sequensyAPI.nonce },
    })
      .then((res) => res.json())
      .then((data) => {
        setSystemInfo(data);
        setSystemInfoLoading(false);
      })
      .catch(() => setSystemInfoLoading(false));
  }, []);

  async function handleSave() {
    try {
      await save();
      toast.success(__('Settings saved'));
    } catch {
      toast.error(__('Failed to save settings'));
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6 max-w-4xl">
        <div>
          <h1 className="seq-page-title">{__('Settings')}</h1>
          <p className="seq-body mt-1">{__('Configure general plugin settings and preferences')}</p>
        </div>
        <SettingsSkeleton />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-4xl pb-20">
      {/* Header */}
      <div>
        <h1 className="seq-page-title">{__('Settings')}</h1>
        <p className="seq-body mt-1">{__('Configure general plugin settings and preferences')}</p>
      </div>

      {error && (
        <div className="bg-error-muted border border-error text-error-text rounded-lg p-3 text-sm">
          {error}
        </div>
      )}

      {/* Pro settings slot — Pro mounts license UI here */}
      <div id="sequensy-pro-settings-slot"></div>

      {/* General Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg text-slate-900 flex items-center gap-2">
            <Wrench className="h-4 w-4 text-slate-400" />
            {__('General Settings')}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-1">
          <SettingRow changed={changedFields.has('debug_mode')}>
            <div className="flex items-center justify-between py-4">
              <div className="space-y-1">
                <Label htmlFor="debug-mode" className="text-sm font-medium text-slate-900">
                  {__('Debug Mode')}
                </Label>
                <p className="text-sm text-slate-500">
                  {__('Enable detailed logging for troubleshooting workflow issues')}
                </p>
              </div>
              <Switch
                id="debug-mode"
                checked={settings.debug_mode}
                onCheckedChange={(val) => updateSetting('debug_mode', val)}
              />
            </div>
          </SettingRow>

          <SettingRow changed={changedFields.has('email_notifications')}>
            <div className="flex items-center justify-between py-4">
              <div className="space-y-1">
                <Label htmlFor="email-notifications" className="text-sm font-medium text-slate-900">
                  {__('Email Notifications')}
                </Label>
                <p className="text-sm text-slate-500">
                  {__('Receive email alerts for workflow errors and failures')}
                </p>
              </div>
              <Switch
                id="email-notifications"
                checked={settings.email_notifications}
                onCheckedChange={(val) => updateSetting('email_notifications', val)}
              />
            </div>
          </SettingRow>

          <SettingRow changed={changedFields.has('log_retention')}>
            <div className="py-4 space-y-2">
              <Label htmlFor="log-retention" className="text-sm font-medium text-slate-900">
                {__('Activity Log Retention')}
              </Label>
              <p className="text-sm text-slate-500">{__('Number of days to keep activity logs')}</p>
              <Select
                value={String(settings.log_retention)}
                onValueChange={(val) => updateSetting('log_retention', Number(val))}
              >
                <SelectTrigger id="log-retention">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="7">7 days</SelectItem>
                  <SelectItem value="14">14 days</SelectItem>
                  <SelectItem value="30">30 days</SelectItem>
                  <SelectItem value="60">60 days</SelectItem>
                  <SelectItem value="90">90 days</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </SettingRow>
        </CardContent>
      </Card>

      {/* Execution Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg text-slate-900 flex items-center gap-2">
            <Play className="h-4 w-4 text-slate-400" />
            {__('Execution Settings')}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-1">
          <SettingRow changed={changedFields.has('max_retries')}>
            <div className="py-4 space-y-2">
              <Label htmlFor="max-retries" className="text-sm font-medium text-slate-900">
                {__('Maximum Retries')}
              </Label>
              <p className="text-sm text-slate-500">
                {__('Number of times to retry a failed action before marking as error')}
              </p>
              <Select
                value={String(settings.max_retries)}
                onValueChange={(val) => updateSetting('max_retries', Number(val))}
              >
                <SelectTrigger id="max-retries">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">No retries</SelectItem>
                  <SelectItem value="1">1 retry</SelectItem>
                  <SelectItem value="2">2 retries</SelectItem>
                  <SelectItem value="3">3 retries</SelectItem>
                  <SelectItem value="5">5 retries</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </SettingRow>

          <SettingRow changed={changedFields.has('retry_delay')}>
            <div className="py-4 space-y-2">
              <Label htmlFor="retry-delay" className="text-sm font-medium text-slate-900">
                {__('Retry Delay')}
              </Label>
              <p className="text-sm text-slate-500">
                {__('Seconds to wait between retry attempts')}
              </p>
              <Select
                value={String(settings.retry_delay)}
                onValueChange={(val) => updateSetting('retry_delay', Number(val))}
              >
                <SelectTrigger id="retry-delay">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0.5">30 seconds</SelectItem>
                  <SelectItem value="1">1 minute</SelectItem>
                  <SelectItem value="5">5 minutes</SelectItem>
                  <SelectItem value="10">10 minutes</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </SettingRow>

          <SettingRow changed={changedFields.has('webhook_timeout')}>
            <div className="py-4 space-y-2">
              <Label htmlFor="webhook-timeout" className="text-sm font-medium text-slate-900">
                {__('Webhook Timeout')}
              </Label>
              <p className="text-sm text-slate-500">
                {__('Maximum seconds to wait for webhook response')}
              </p>
              <Select
                value={String(settings.webhook_timeout)}
                onValueChange={(val) => updateSetting('webhook_timeout', Number(val))}
              >
                <SelectTrigger id="webhook-timeout">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="15">15 seconds</SelectItem>
                  <SelectItem value="30">30 seconds</SelectItem>
                  <SelectItem value="60">60 seconds</SelectItem>
                  <SelectItem value="120">120 seconds</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </SettingRow>
        </CardContent>
      </Card>

      {/* System Information — Collapsed */}
      <Accordion type="single" collapsible>
        <AccordionItem value="system-info" className="border rounded-lg px-4">
          <AccordionTrigger className="hover:no-underline">
            <span className="flex items-center gap-2 text-sm font-medium text-slate-600">
              <Monitor className="h-4 w-4 text-slate-400" />
              {__('System Information')}
            </span>
          </AccordionTrigger>
          <AccordionContent>
            {systemInfoLoading ? (
              <div className="text-sm text-slate-500">{__('Loading...')}</div>
            ) : (
              <div className="grid grid-cols-2 gap-4 pb-2">
                <InfoItem label={__('Plugin Version')} value={systemInfo?.plugin_version} />
                <InfoItem
                  label={__('Action Scheduler')}
                  value={systemInfo?.action_scheduler_version}
                />
                <InfoItem label={__('WordPress')} value={systemInfo?.wordpress_version} />
                <InfoItem label={__('PHP')} value={systemInfo?.php_version} />
              </div>
            )}
          </AccordionContent>
        </AccordionItem>
      </Accordion>

      {/* Sticky Save Bar */}
      <SettingsSaveBar
        isDirty={isDirty}
        isSaving={isSaving}
        onSave={handleSave}
        onDiscard={discard}
      />
    </div>
  );
}

function SettingRow({ changed, children }: { changed: boolean; children: React.ReactNode }) {
  return (
    <div
      className={cn(
        'px-3 -mx-3 rounded-md transition-all duration-200',
        changed
          ? 'border-l-2 border-l-cyan-500 bg-cyan-50/40'
          : 'border-l-2 border-l-transparent hover:bg-slate-50',
      )}
    >
      {children}
    </div>
  );
}

function InfoItem({ label, value }: { label: string; value?: string }) {
  return (
    <div className="space-y-1">
      <div className="text-sm text-slate-500">{label}</div>
      <div className="text-sm font-medium text-slate-900">{value || 'Unknown'}</div>
    </div>
  );
}

function SettingsSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-24 w-full rounded-lg" />
      <div className="border rounded-lg p-6 space-y-6">
        <Skeleton className="h-5 w-40" />
        <div className="space-y-4">
          <div className="flex justify-between items-center">
            <div className="space-y-2">
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-3 w-64" />
            </div>
            <Skeleton className="h-6 w-10 rounded-full" />
          </div>
          <div className="flex justify-between items-center">
            <div className="space-y-2">
              <Skeleton className="h-4 w-32" />
              <Skeleton className="h-3 w-56" />
            </div>
            <Skeleton className="h-6 w-10 rounded-full" />
          </div>
          <div className="space-y-2">
            <Skeleton className="h-4 w-36" />
            <Skeleton className="h-3 w-48" />
            <Skeleton className="h-10 w-full rounded-md" />
          </div>
        </div>
      </div>
      <div className="border rounded-lg p-6 space-y-6">
        <Skeleton className="h-5 w-44" />
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="space-y-2">
              <Skeleton className="h-4 w-28" />
              <Skeleton className="h-3 w-60" />
              <Skeleton className="h-10 w-full rounded-md" />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
