import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { useStudioStore } from '../store';
import { useShallow } from 'zustand/shallow';
import { createQueryByRoutes } from '@kevisual/query/api'
import { useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Copy, Check } from 'lucide-react';
import { toast } from 'sonner';
import { useState } from 'react';
import { pick } from 'es-toolkit';
export const ExportDialog = () => {
  const { showExportDialog, setShowExportDialog, exportRoutes } = useStudioStore(
    useShallow((state) => ({
      showExportDialog: state.showExportDialog,
      setShowExportDialog: state.setShowExportDialog,
      exportRoutes: state.exportRoutes,
    }))
  );
  const [copied, setCopied] = useState(false);

  const code = useMemo(() => {
    if (!exportRoutes) return '';
    let routeInfo = exportRoutes.map(route => pick(route, ['path', 'key', 'id', 'description', 'metadata']));
    const query = createQueryByRoutes(routeInfo as any);
    return query;
  }, [exportRoutes]);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      toast.success('代码已复制到剪贴板');
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      toast.error('复制失败，请重试');
    }
  };

  return (
    <Dialog open={showExportDialog} onOpenChange={setShowExportDialog}>
      <DialogContent className="max-w-3xl! max-h-[80vh] overflow-hidden">
        <DialogHeader>
          <DialogTitle>导出API代码</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 w-full overflow-hidden">
          <div className="p-4 border border-gray-300 rounded-md bg-gray-50">
            <pre className="text-xs max-h-[60vh] overflow-auto scrollbar">
              {code}
            </pre>
          </div>
        </div>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => setShowExportDialog(false)}
          >
            取消
          </Button>
          <Button
            onClick={handleCopy}
            className="gap-2"
          >
            {copied ? (
              <>
                <Check size={16} />
                已复制
              </>
            ) : (
              <>
                <Copy size={16} />
                复制代码
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
