/**
 * RestoreDialog Component
 *
 * 检查点恢复确认对话框：显示安全检查、选择恢复模式、确认操作
 */

import { useState, useEffect, useCallback } from 'react';
import {
  X,
  AlertTriangle,
  AlertCircle,
  CheckCircle,
  RotateCcw,
  FileText,
  Loader2,
} 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 { Skeleton } from './Skeleton';
import {
  getCheckpoint,
  checkSafety,
  previewRestore,
  restoreCheckpoint,
  type CheckpointDetail,
  type SafetyCheckResult,
  type RestoreResult,
  type RestoreMode,
} from '../api/client.js';

interface RestoreDialogProps {
  /** 检查点 ID */
  checkpointId: string;
  /** 要恢复的文件列表（可选，为空则恢复全部） */
  files?: string[];
  /** 关闭回调 */
  onClose: () => void;
  /** 恢复成功回调 */
  onRestored?: (result: RestoreResult) => void;
  /** 是否启用响应式布局 */
  responsive?: boolean;
}

// 恢复模式选项
const RESTORE_MODES: { value: RestoreMode; label: string; description: string }[] = [
  {
    value: 'ai_changes_only',
    label: 'AI Changes Only',
    description: 'Only restore files that were modified by AI',
  },
  {
    value: 'workspace_only',
    label: 'Workspace Only',
    description: 'Only restore workspace changes (not AI modifications)',
  },
  {
    value: 'full',
    label: 'Full Restore',
    description: 'Restore all files to checkpoint state',
  },
];

export function RestoreDialog({
  checkpointId,
  files,
  onClose,
  onRestored,
  responsive = false,
}: RestoreDialogProps) {
  // 数据状态
  const [checkpoint, setCheckpoint] = useState<CheckpointDetail | null>(null);
  const [safetyResult, setSafetyResult] = useState<SafetyCheckResult | null>(null);
  const [previewResult, setPreviewResult] = useState<RestoreResult | null>(null);

  // 表单状态
  const [selectedMode, setSelectedMode] = useState<RestoreMode>('full');
  const [skipSafetyCheck, setSkipSafetyCheck] = useState(false);

  // UI 状态
  const [loading, setLoading] = useState(true);
  const [restoring, setRestoring] = useState(false);

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      const [cpResult, safetyRes, previewRes] = await Promise.all([
        getCheckpoint(checkpointId),
        checkSafety(checkpointId),
        previewRestore(checkpointId, { mode: selectedMode, files }),
      ]);

      if (cpResult.success && cpResult.data) {
        setCheckpoint(cpResult.data);
      } else {
        toast.error(cpResult.error || 'Failed to load checkpoint');
      }

      if (safetyRes.success && safetyRes.data) {
        setSafetyResult(safetyRes.data);
      }

      if (previewRes.success && previewRes.data) {
        setPreviewResult(previewRes.data);
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to load data');
    }
  }, [checkpointId, selectedMode, files]);

  // 初始加载
  useEffect(() => {
    setLoading(true);
    loadData().finally(() => setLoading(false));
  }, [loadData]);

  // 模式变化时重新预览
  useEffect(() => {
    if (!loading) {
      previewRestore(checkpointId, { mode: selectedMode, files })
        .then((result) => {
          if (result.success && result.data) {
            setPreviewResult(result.data);
          }
        })
        .catch(() => {});
    }
  }, [checkpointId, selectedMode, files, loading]);

  // 执行恢复
  const handleRestore = async () => {
    setRestoring(true);
    try {
      const result = await restoreCheckpoint(checkpointId, {
        mode: selectedMode,
        files,
        skipSafetyCheck,
      });

      if (result.success && result.data) {
        toast.success(`Restored ${result.data.restoredFiles.length} files`);
        onRestored?.(result.data);
        onClose();
      } else {
        toast.error(result.error || 'Failed to restore checkpoint');
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to restore');
    } finally {
      setRestoring(false);
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => new Date(timestamp).toLocaleString();

  // Loading 骨架屏
  const LoadingSkeleton = () => (
    <div className="space-y-4 p-4">
      <Skeleton className="h-6 w-48" />
      <Skeleton className="h-20 w-full" />
      <Skeleton className="h-32 w-full" />
    </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-hidden flex flex-col',
            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(
              'flex items-center justify-between border-b border-line',
              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-emphasis rounded-full md:hidden" />
            )}
            <div className={cn(responsive && 'mt-2 md:mt-0')}>
              <h2 className="text-lg font-semibold flex items-center gap-2">
                <RotateCcw size={20} className="text-primary-400" />
                Restore Checkpoint
              </h2>
              {checkpoint && (
                <p className="text-xs text-fg-subtle">
                  {formatTime(checkpoint.timestamp)}
                </p>
              )}
            </div>
            <Button
              variant="ghost"
              size="icon"
              onClick={onClose}
              className={cn(responsive && 'min-w-[44px] min-h-[44px]')}
            >
              <X size={20} />
            </Button>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {loading ? (
              <LoadingSkeleton />
            ) : (
              <>
                {/* Safety Check Results */}
                {safetyResult && (
                  <div className="space-y-2">
                    {/* Errors */}
                    {safetyResult.errors.length > 0 && (
                      <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                        <div className="flex items-center gap-2 text-red-400 mb-2">
                          <AlertCircle size={16} />
                          <span className="font-medium">Safety Errors</span>
                        </div>
                        <ul className="text-sm text-red-300 space-y-1">
                          {safetyResult.errors.map((error, i) => (
                            <li key={i} className="flex items-start gap-2">
                              <span className="text-red-500">•</span>
                              {error}
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}

                    {/* Warnings */}
                    {safetyResult.warnings.length > 0 && (
                      <div className="p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
                        <div className="flex items-center gap-2 text-yellow-400 mb-2">
                          <AlertTriangle size={16} />
                          <span className="font-medium">Warnings</span>
                        </div>
                        <ul className="text-sm text-yellow-300 space-y-1">
                          {safetyResult.warnings.map((warning, i) => (
                            <li key={i} className="flex items-start gap-2">
                              <span className="text-yellow-500">•</span>
                              {warning}
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}

                    {/* Safe */}
                    {safetyResult.safe && safetyResult.errors.length === 0 && safetyResult.warnings.length === 0 && (
                      <div className="p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
                        <div className="flex items-center gap-2 text-green-400">
                          <CheckCircle size={16} />
                          <span className="font-medium">Safety check passed</span>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Restore Mode Selection */}
                {!files && (
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-fg-secondary">Restore Mode</label>
                    <div className="space-y-2">
                      {RESTORE_MODES.map((mode) => (
                        <label
                          key={mode.value}
                          className={cn(
                            'flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-colors',
                            selectedMode === mode.value
                              ? 'bg-primary-500/10 border border-primary-500/50'
                              : 'bg-surface-base/50 border border-line hover:border-line-muted'
                          )}
                        >
                          <input
                            type="radio"
                            name="restoreMode"
                            value={mode.value}
                            checked={selectedMode === mode.value}
                            onChange={(e) => setSelectedMode(e.target.value as RestoreMode)}
                            className="mt-1"
                          />
                          <div>
                            <div className="font-medium text-fg-secondary">{mode.label}</div>
                            <div className="text-xs text-fg-subtle">{mode.description}</div>
                          </div>
                        </label>
                      ))}
                    </div>
                  </div>
                )}

                {/* Files to Restore */}
                {previewResult && previewResult.restoredFiles.length > 0 && (
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-fg-secondary flex items-center gap-2">
                      <FileText size={14} />
                      Files to restore ({previewResult.restoredFiles.length})
                    </label>
                    <div className="max-h-40 overflow-y-auto bg-surface-base/50 rounded-lg p-2 space-y-1">
                      {previewResult.restoredFiles.map((file) => (
                        <div
                          key={file}
                          className="text-xs font-mono text-fg-muted px-2 py-1 hover:bg-surface-subtle rounded"
                        >
                          {file}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Skip Safety Check Option */}
                {safetyResult && !safetyResult.safe && (
                  <label className="flex items-center gap-2 text-sm text-fg-muted cursor-pointer">
                    <input
                      type="checkbox"
                      checked={skipSafetyCheck}
                      onChange={(e) => setSkipSafetyCheck(e.target.checked)}
                      className="rounded"
                    />
                    Skip safety check and proceed anyway
                  </label>
                )}
              </>
            )}
          </div>

          {/* Footer */}
          <div
            className={cn(
              'flex items-center justify-end gap-3 border-t border-line',
              responsive ? 'px-4 py-3 safe-area-pb' : 'px-6 py-3'
            )}
          >
            <Button variant="ghost" onClick={onClose}>
              Cancel
            </Button>
            <Button
              variant="default"
              onClick={handleRestore}
              disabled={
                loading ||
                restoring ||
                (safetyResult && !safetyResult.safe && !skipSafetyCheck) ||
                !previewResult ||
                previewResult.restoredFiles.length === 0
              }
            >
              {restoring ? (
                <>
                  <Loader2 size={16} className="mr-2 animate-spin" />
                  Restoring...
                </>
              ) : (
                <>
                  <RotateCcw size={16} className="mr-2" />
                  Restore Now
                </>
              )}
            </Button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
