/**
 * ConfigPanel Component
 *
 * 支持响应式：responsive=true 时移动端全屏显示，桌面端居中弹窗
 */

import { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { cn } from '../utils/cn';
import { modalOverlay, modalContent, smoothTransition } from '../utils/animations';
import { Button } from '../primitives/Button';
import { Input } from '../primitives/Input';
import { Skeleton } from './Skeleton';
import {
  getConfig,
  updateConfig,
  type ServerConfig,
} from '../api/client.js';

interface ConfigPanelProps {
  onClose: () => void;
  /** 是否启用响应式布局（移动端全屏面板） */
  responsive?: boolean;
}

export function ConfigPanel({ onClose, responsive = false }: ConfigPanelProps) {
  const [config, setConfig] = useState<ServerConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // 表单状态
  const [formData, setFormData] = useState({
    workdir: '',
  });

  // 加载配置
  useEffect(() => {
    async function loadConfig() {
      try {
        const configResponse = await getConfig();

        setConfig(configResponse.data);
        setFormData({
          workdir: configResponse.data.workdir,
        });
      } catch (err) {
        toast.error(err instanceof Error ? err.message : 'Failed to load config');
      } finally {
        setLoading(false);
      }
    }
    loadConfig();
  }, []);

  // 保存配置
  const handleSave = async () => {
    setSaving(true);

    try {
      const response = await updateConfig(formData);
      setConfig(response.data);
      toast.success('Settings saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save config');
    } finally {
      setSaving(false);
    }
  };

  // 重置为默认值
  const handleReset = () => {
    if (config) {
      setFormData({
        workdir: config.workdir,
      });
      toast.info('Settings reset');
    }
  };

  // Loading 骨架屏
  const LoadingSkeleton = () => (
    <div className="space-y-6 p-6">
      {[1, 2, 3, 4].map((i) => (
        <div key={i} className="space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-10 w-full" />
        </div>
      ))}
    </div>
  );

  return (
    <AnimatePresence>
      <motion.div
        variants={modalOverlay}
        initial="initial"
        animate="animate"
        exit="exit"
        transition={{ duration: 0.2 }}
        className={cn(
          'fixed inset-0 bg-black/50 flex z-50',
          responsive ? 'items-end md:items-center justify-center' : 'items-center justify-center'
        )}
        onClick={onClose}
      >
        <motion.div
          variants={modalContent}
          initial="initial"
          animate="animate"
          exit="exit"
          transition={smoothTransition}
          onClick={(e) => e.stopPropagation()}
          className={cn(
            'bg-surface-subtle max-h-[90vh] overflow-auto',
            responsive
              ? 'w-full md:w-full md:max-w-lg md:mx-4 rounded-t-2xl md:rounded-lg'
              : 'rounded-lg w-full max-w-lg mx-4'
          )}
        >
          {/* Header */}
          <div
            className={cn(
              'sticky top-0 flex items-center justify-between border-b border-line bg-surface-subtle z-10',
              responsive ? 'px-4 md:px-6 py-4' : 'px-6 py-4'
            )}
          >
            {responsive && (
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-surface-muted rounded-full md:hidden" />
            )}
            <h2 className={cn('text-lg font-semibold', responsive && 'mt-2 md:mt-0')}>
              Settings
            </h2>
            <Button
              variant="ghost"
              size="icon"
              onClick={onClose}
              className={cn(
                responsive && 'min-w-[44px] min-h-[44px]'
              )}
            >
              <X size={20} />
            </Button>
          </div>

          {/* Content */}
          {loading ? (
            <LoadingSkeleton />
          ) : (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.1 }}
              className={cn('space-y-6', responsive ? 'p-4 md:p-6' : 'p-6')}
            >
              {/* Working Directory */}
              <div className="space-y-2">
                <label className="block text-sm font-medium text-fg-secondary">Working Directory</label>
                <Input
                  value={formData.workdir}
                  onChange={(e) => setFormData({ ...formData, workdir: e.target.value })}
                  className="font-mono"
                  placeholder="/path/to/project"
                />
                <p className="text-xs text-fg-subtle">Root directory for file operations</p>
              </div>
            </motion.div>
          )}

          {/* Footer */}
          <div
            className={cn(
              'sticky bottom-0 border-t border-line bg-surface-subtle',
              responsive
                ? 'flex flex-col-reverse md:flex-row items-stretch md:items-center justify-end gap-2 md:gap-3 p-4 md:px-6 md:py-4 safe-area-pb'
                : 'flex items-center justify-end gap-3 px-6 py-4 bg-surface-subtle/50'
            )}
          >
            <Button
              variant="ghost"
              onClick={handleReset}
              className={cn(responsive && 'justify-center')}
            >
              Reset
            </Button>
            <Button
              variant="secondary"
              onClick={onClose}
              className={cn(responsive && 'justify-center')}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={saving || loading}
              className={cn(responsive && 'justify-center')}
            >
              {saving ? 'Saving...' : 'Save Changes'}
            </Button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
