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, useEffect } from 'react';
import { clone, cloneDeep, pick } from 'es-toolkit';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
type CreateOptions = {
  removeViewItem?: boolean;
  before?: string;
  after?: string;
}
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 [before, setBefore] = useState(() => {
    const defaultBefore = `import { createQueryApi } from '@kevisual/query/api';`;  
    if (typeof window !== 'undefined') {
      return localStorage.getItem('exportBefore') || defaultBefore;
    }
    return defaultBefore;
  });
  const [after, setAfter] = useState(() => {
    const defaultAfter = `const queryApi = createQueryApi({ api });\n\nexport { queryApi };`;
    if (typeof window !== 'undefined') {
      return localStorage.getItem('exportAfter') || defaultAfter;
    }
    return defaultAfter;
  });
  const [removeViewItem, setRemoveViewItem] = useState(() => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('exportRemoveViewItem') === 'true';
    }
    return false;
  });

  // 保存配置到 localStorage
  useEffect(() => {
    localStorage.setItem('exportBefore', before);
  }, [before]);

  useEffect(() => {
    localStorage.setItem('exportAfter', after);
  }, [after]);

  useEffect(() => {
    localStorage.setItem('exportRemoveViewItem', String(removeViewItem));
  }, [removeViewItem]);

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

  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-4xl! max-h-[80vh] overflow-hidden">
        <DialogHeader>
          <DialogTitle>导出API代码</DialogTitle>
        </DialogHeader>
        <div className="flex gap-4 w-full overflow-hidden">
          <div className="w-90 shrink-0 space-y-4">
            <div className="space-y-2">
              <Label htmlFor="before">Before (import)</Label>
              <Textarea
                id="before"
                value={before}
                onChange={(e) => setBefore(e.target.value)}
                placeholder="import ..."
                rows={3}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="after">After (export)</Label>
              <Textarea
                id="after"
                value={after}
                onChange={(e) => setAfter(e.target.value)}
                placeholder="export ..."
                rows={3}
              />
            </div>
            <div className="flex items-center gap-2">
              <Checkbox
                id="removeViewItem"
                checked={removeViewItem}
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  setRemoveViewItem(value);
                }}
              />
              <Label htmlFor="removeViewItem">Remove View Item</Label>
            </div>
          </div>
          <div className="flex-1 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>
  );
};
