import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { GripVertical } from 'lucide-react';

export interface ColumnDef {
  key: string;
  label: string;
  required?: boolean;
}

interface ColumnConfigDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  columns: ColumnDef[];
  visibleCols: Set<string>;
  orderedKeys?: string[];
  onConfirm: (config: { visibleCols: Set<string>; orderedKeys: string[] }) => void;
}

export function ColumnConfigDialog({
  open,
  onOpenChange,
  columns,
  visibleCols,
  orderedKeys,
  onConfirm,
}: ColumnConfigDialogProps) {
  const [draft, setDraft] = useState<Set<string>>(new Set(visibleCols));
  const [draftOrder, setDraftOrder] = useState<string[]>(orderedKeys ?? columns.map(column => column.key));
  const [draggingKey, setDraggingKey] = useState<string | null>(null);
  const [dragOverKey, setDragOverKey] = useState<string | null>(null);

  const resolvedOrder = orderedKeys ?? columns.map(column => column.key);

  useEffect(() => {
    if (!open) return;
    setDraft(new Set(visibleCols));
    setDraftOrder(resolvedOrder);
    setDraggingKey(null);
    setDragOverKey(null);
  }, [open, visibleCols, resolvedOrder]);

  const optionalCols = columns.filter(c => !c.required);
  const columnByKey = new Map(columns.map(column => [column.key, column]));

  function toggle(key: string) {
    setDraft(prev => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  }

  function selectAll() {
    setDraft(prev => {
      const next = new Set(prev);
      optionalCols.forEach(c => next.add(c.key));
      return next;
    });
  }

  function selectNone() {
    setDraft(prev => {
      const next = new Set(prev);
      optionalCols.forEach(c => next.delete(c.key));
      return next;
    });
  }

  function handleConfirm() {
    onConfirm({ visibleCols: draft, orderedKeys: draftOrder });
    onOpenChange(false);
  }

  function handleDragStart(key: string) {
    if (columnByKey.get(key)?.required) return;
    setDraggingKey(key);
  }

  function handleDragOver(key: string) {
    if (!draggingKey || draggingKey === key || columnByKey.get(key)?.required) return;
    setDragOverKey(key);
  }

  function handleDrop(targetKey: string) {
    if (!draggingKey || draggingKey === targetKey) return;
    if (columnByKey.get(draggingKey)?.required || columnByKey.get(targetKey)?.required) return;

    setDraftOrder(prev => {
      const fromIndex = prev.indexOf(draggingKey);
      const toIndex = prev.indexOf(targetKey);
      if (fromIndex === -1 || toIndex === -1) return prev;

      const next = [...prev];
      const [moved] = next.splice(fromIndex, 1);
      next.splice(toIndex, 0, moved);
      return next;
    });

    setDragOverKey(null);
    setDraggingKey(null);
  }

  function handleDragEnd() {
    setDraggingKey(null);
    setDragOverKey(null);
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[640px]">
        <DialogHeader>
          <DialogTitle>列显示配置</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/30 px-3 py-2.5">
            <div className="flex flex-wrap gap-2">
              <button
                type="button"
                onClick={selectAll}
                className="rounded-md border border-border bg-background px-2.5 py-1 text-xs text-primary transition-colors hover:bg-primary/5"
              >
                全选
              </button>
              <button
                type="button"
                onClick={selectNone}
                className="rounded-md border border-border bg-background px-2.5 py-1 text-xs text-primary transition-colors hover:bg-primary/5"
              >
                全不选
              </button>
            </div>
            <div className="text-xs text-muted-foreground">已选中 {draft.size} 项</div>
          </div>

          <div>
            <div className="mb-2 flex items-center justify-between px-1">
              <span className="text-xs font-medium text-foreground">列项目</span>
            </div>
            <div className="grid max-h-[420px] gap-2 overflow-y-auto pr-1 sm:grid-cols-2">
              {draftOrder.map(key => {
                const col = columnByKey.get(key);
                if (!col) return null;

                return (
                  <div
                    key={col.key}
                    draggable={!col.required}
                    onDragStart={() => handleDragStart(col.key)}
                    onDragOver={event => {
                      event.preventDefault();
                      handleDragOver(col.key);
                    }}
                    onDrop={event => {
                      event.preventDefault();
                      handleDrop(col.key);
                    }}
                    onDragEnd={handleDragEnd}
                    className={`flex items-center gap-2 rounded-md border px-2 py-1.5 ${col.required ? 'bg-muted/40' : 'cursor-move'} ${draggingKey === col.key ? 'border-primary bg-primary/5 opacity-60' : dragOverKey === col.key ? 'border-primary/70 bg-primary/10' : 'border-border'}`}
                  >
                    <label className={`flex min-w-0 flex-1 items-center gap-2 select-none ${col.required ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}>
                      <Checkbox
                        checked={draft.has(col.key)}
                        disabled={col.required}
                        onCheckedChange={() => !col.required && toggle(col.key)}
                      />
                      <span className="truncate text-xs leading-none">{col.label}</span>
                      {col.required && (
                        <span className="shrink-0 text-[10px] text-muted-foreground">固定</span>
                      )}
                    </label>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="h-5 w-5 shrink-0 cursor-grab text-muted-foreground active:cursor-grabbing"
                      disabled={col.required}
                      aria-label={`拖拽排序 ${col.label}`}
                    >
                      <GripVertical className="h-3 w-3" />
                    </Button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleConfirm}>确认</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
