"use client";

import * as React from "react";
import { format } from "date-fns";
import { GitBranch, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Pipeline } from "@/api/rtk/pipelines-api";
import { Badge } from "@/components/ui/badge";

interface PipelineTableProps {
  pipelines: Pipeline[];
  isAdmin: boolean;
  onEdit: (pipeline: Pipeline) => void;
  onDelete: (pipeline: Pipeline) => void;
  onViewStages: (pipeline: Pipeline, stages: any[]) => void;
}

const formatTs = (dateString: string | undefined) => {
  if (!dateString) return "—";
  try {
    return format(new Date(dateString), "MMM d, yyyy");
  } catch {
    return "Invalid date";
  }
};

const parseStages = (stages: any) => {
  if (!Array.isArray(stages)) return [];
  return stages.filter((stage) => {
    if (!stage || typeof stage !== "object") return false;
    const candidate = stage as unknown as Record<string, unknown>;
    return (
      typeof candidate.id === "string" &&
      typeof candidate.name === "string"
    );
  });
};

const sortStagesForDisplay = (stages: any[]) => {
  return stages.sort((a, b) => {
    const aOrder = a.sortOrder ?? 999999;
    const bOrder = b.sortOrder ?? 999999;
    return aOrder - bOrder;
  });
};

export function PipelineTable({
  pipelines,
  isAdmin,
  onEdit,
  onDelete,
  onViewStages,
}: PipelineTableProps) {
  return (
    <div className="flex-1 min-h-0 overflow-auto scrollbar-themed">
      <Table variant="transparent">
        <TableHeader>
          <TableRow className="bg-muted/40 border-b border-border hover:bg-muted/40">
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
              Pipeline
            </TableHead>
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[72px] text-center">
              Count
            </TableHead>
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[120px]">
              View
            </TableHead>
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[180px]">
              Modules
            </TableHead>
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[120px] hidden lg:table-cell">
              Created
            </TableHead>
            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[108px] hidden md:table-cell">
              Updated
            </TableHead>
            <TableHead className="text-right text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] w-[100px]">
              Actions
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {pipelines.map((pipeline) => {
            const stageList = sortStagesForDisplay(
              parseStages(pipeline.stages),
            );
            return (
              <TableRow
                key={pipeline.id}
                className="border-b border-border/60 hover:bg-muted/20 transition-colors"
              >
                <TableCell className="py-3">
                  <div className="flex items-start gap-2 min-w-0">
                    <div className="h-7 w-7 rounded-lg bg-accent/10 flex items-center justify-center text-accent shrink-0 mt-0.5">
                      <GitBranch size={14} />
                    </div>
                    <div className="min-w-0">
                      <p className="text-[13px] font-semibold text-text truncate">
                        {pipeline.name}
                      </p>
                      <p className="text-[10px] text-gray-400 font-mono truncate mt-0.5">
                        {pipeline.id}
                      </p>
                    </div>
                  </div>
                </TableCell>
                <TableCell className="py-3 align-top text-center">
                  <span className="text-[13px] font-bold text-text tabular-nums">
                    {stageList.length}
                  </span>
                </TableCell>
                <TableCell className="py-3 align-top">
                  {stageList.length === 0 ? (
                    <span className="text-[12px] text-gray-400 italic">
                      —
                    </span>
                  ) : (
                    <Button
                      type="button"
                      variant="link"
                      className="h-auto p-0 text-[12px] font-bold text-accent font-['Lexend_Deca'] underline-offset-4"
                      onClick={() =>
                        onViewStages(pipeline, stageList)
                      }
                    >
                      View stages
                    </Button>
                  )}
                </TableCell>
                <TableCell className="py-3 align-top">
                  <div className="flex flex-wrap gap-1 max-w-[200px]">
                    {pipeline.moduleDependencies && pipeline.moduleDependencies.length > 0 ? (
                      pipeline.moduleDependencies.map((mod) => (
                        <Badge
                          key={mod}
                          variant="secondary"
                          className="px-1.5 py-0 rounded-md text-[10px] font-bold bg-accent/5 text-accent border-accent/10 whitespace-nowrap"
                        >
                          {mod}
                        </Badge>
                      ))
                    ) : (
                      <span className="text-[12px] text-gray-400 italic">None</span>
                    )}
                  </div>
                </TableCell>
                <TableCell className="py-3 align-top text-[12px] text-gray-600 hidden lg:table-cell whitespace-nowrap">
                  {formatTs(pipeline.createdAt)}
                </TableCell>
                <TableCell className="py-3 align-top text-[12px] text-gray-600 hidden md:table-cell whitespace-nowrap">
                  {formatTs(pipeline.updatedAt)}
                </TableCell>
                <TableCell className="py-3 align-top text-right">
                  <div className="flex items-center justify-end gap-1">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-gray-700 hover:text-accent"
                          onClick={() => onEdit(pipeline)}
                          disabled={!isAdmin}
                        >
                          <Pencil size={14} />
                        </Button>
                      </TooltipTrigger>
                      {!isAdmin && (
                        <TooltipContent>
                          Only admins can edit pipelines
                        </TooltipContent>
                      )}
                    </Tooltip>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-gray-700 hover:text-destructive"
                          onClick={() => onDelete(pipeline)}
                          disabled={!isAdmin}
                        >
                          <Trash2 size={14} />
                        </Button>
                      </TooltipTrigger>
                      {!isAdmin ? (
                        <TooltipContent>
                          Only admins can delete pipelines
                        </TooltipContent>
                      ) : stageList.length > 0 ? (
                        <TooltipContent>
                          Remove all stages first (Pipeline → Stages) before deleting — you will be reminded if you try now
                        </TooltipContent>
                      ) : null}
                    </Tooltip>
                  </div>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </div>
  );
}
