import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { useColumnDetails } from "@/hooks/use-schema";
import { insertRow } from "@/lib/tauri";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  connectionId: string;
  schema: string;
  table: string;
  onSuccess: () => void;
}

export function InsertRowDialog({
  open,
  onOpenChange,
  connectionId,
  schema,
  table,
  onSuccess,
}: Props) {
  const { data: columns } = useColumnDetails(
    open ? connectionId : null,
    open ? schema : null,
    open ? table : null
  );
  const [values, setValues] = useState<Record<string, string>>({});
  const [skipColumns, setSkipColumns] = useState<Set<string>>(new Set());
  const [isInserting, setIsInserting] = useState(false);

  useEffect(() => {
    if (open && columns) {
      const initial: Record<string, string> = {};
      const skip = new Set<string>();
      for (const col of columns) {
        if (col.is_identity || col.column_default?.startsWith("nextval(")) {
          skip.add(col.column_name);
        } else if (col.column_default != null) {
          initial[col.column_name] = col.column_default;
        } else {
          initial[col.column_name] = "";
        }
      }
      setValues(initial);
      setSkipColumns(skip);
    }
  }, [open, columns]);

  const handleInsert = async () => {
    if (!columns) return;
    setIsInserting(true);
    try {
      const cols: string[] = [];
      const vals: unknown[] = [];
      for (const col of columns) {
        if (skipColumns.has(col.column_name)) continue;
        const val = values[col.column_name];
        if (val === "" && col.is_nullable) {
          cols.push(col.column_name);
          vals.push(null);
        } else if (val !== undefined) {
          cols.push(col.column_name);
          vals.push(val);
        }
      }
      await insertRow({ connectionId, schema, table, columns: cols, values: vals });
      toast.success("Row inserted");
      onOpenChange(false);
      onSuccess();
    } catch (err) {
      toast.error("Insert failed", { description: String(err) });
    } finally {
      setIsInserting(false);
    }
  };

  const toggleSkip = (colName: string) => {
    setSkipColumns((prev) => {
      const next = new Set(prev);
      if (next.has(colName)) {
        next.delete(colName);
      } else {
        next.add(colName);
      }
      return next;
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[560px] max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Insert Row into {table}</DialogTitle>
        </DialogHeader>

        <div className="grid gap-2 py-2">
          {columns?.map((col) => {
            const isSkipped = skipColumns.has(col.column_name);
            return (
              <div key={col.column_name} className="grid grid-cols-4 items-center gap-2">
                <div className="flex items-center gap-1 col-span-1 justify-end">
                  <span className="text-sm truncate">{col.column_name}</span>
                  <Badge variant="outline" className="text-[9px] px-1 py-0 shrink-0">
                    {col.data_type}
                  </Badge>
                </div>
                <div className="col-span-3 flex items-center gap-1">
                  {isSkipped ? (
                    <span className="text-xs text-muted-foreground italic flex-1 px-2">
                      auto-generated
                    </span>
                  ) : (
                    <Input
                      className="flex-1 text-sm"
                      value={values[col.column_name] ?? ""}
                      onChange={(e) =>
                        setValues((prev) => ({ ...prev, [col.column_name]: e.target.value }))
                      }
                      placeholder={
                        col.is_nullable ? "NULL" : col.column_default ?? ""
                      }
                    />
                  )}
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 text-[10px] shrink-0"
                    onClick={() => toggleSkip(col.column_name)}
                  >
                    {isSkipped ? "Include" : "Skip"}
                  </Button>
                </div>
              </div>
            );
          })}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleInsert} disabled={isInserting}>
            {isInserting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Insert
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
