"use client";

import * as React from "react";
import {
  GitBranch,
  Edit2,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Plus,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { PipelineStageRow } from "@/api/rtk/pipelines-api";
import { StagesTableProps } from "@/types/deals";
import { cn } from "@/lib/utils";
import { ChevronDown } from "lucide-react";

export function StagesTable({
  rows,
  groups,
  isAdmin,
  onEdit,
  onDelete,
  onAddSubStage,
  getSubStages,
  onEditSubStage,
  onDeleteSubStage,
  page,
  totalPages,
  total,
  onPageChange,
}: StagesTableProps) {
  const [expandedRows, setExpandedRows] = React.useState<Set<string>>(new Set());

  const toggleRow = (id: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const renderSubStages = React.useCallback(
    (row: PipelineStageRow) => {
      const subStages = getSubStages?.(row) ?? [];

      return (
        <div className="mt-1.5 space-y-2.5 animate-in fade-in slide-in-from-top-1 duration-200">
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-2.5">
               <div className="flex items-center gap-2 bg-gray-100/60 px-2.5 py-1 rounded-lg border border-border/40">
                  <span className="text-[10px] font-black uppercase tracking-[0.15em] text-gray-500 font-['Lexend_Deca']">
                    Sub Stages
                  </span>
                  <div className="h-3.5 w-[1px] bg-gray-300" />
                  <span className="text-[10px] font-black text-accent tabular-nums">
                    {subStages.length}
                  </span>
               </div>
               
               {isAdmin && onAddSubStage && (
                 <Button
                   type="button"
                   variant="ghost"
                   className="h-7 rounded-lg px-2 text-[10px] font-bold text-accent hover:bg-accent/10 hover:text-accent transition-all flex items-center gap-1.5"
                   onClick={() => onAddSubStage(row)}
                 >
                   <Plus size={12} className="stroke-[3.5px]" />
                   ADD NEW
                 </Button>
               )}
            </div>
          </div>

          <div className="flex flex-wrap gap-2.5">
            {subStages.length > 0 ? (
              subStages
                .slice()
                .sort((a, b) => a.sortOrder - b.sortOrder)
                .map((subStage, index) => (
                  <div
                    key={subStage.id}
                    className="group flex items-center gap-3 pl-1 pr-1.5 py-1 bg-white border border-border/60 rounded-[14px] shadow-[0_1px_3px_rgba(0,0,0,0.02)] hover:shadow-premium hover:border-accent/40 hover:-translate-y-0.5 transition-all duration-300 cursor-default"
                  >
                    <div className="size-6 shrink-0 flex items-center justify-center rounded-[10px] bg-gray-50 text-[10px] font-black text-gray-400 group-hover:bg-accent group-hover:text-white transition-all duration-300">
                      {index + 1}
                    </div>
                    
                    <div className="flex flex-col min-w-0 pr-1">
                      <span className="text-[12.5px] font-bold text-gray-800 font-['Lexend_Deca'] leading-none truncate max-w-[140px] md:max-w-[200px]">
                        {subStage.name}
                      </span>
                      {typeof subStage.prob === "number" && (
                        <div className="flex items-center gap-1.5 mt-1.5">
                           <div className="flex-1 w-10 h-0.5 bg-gray-100 rounded-full overflow-hidden">
                              <div 
                                className="h-full bg-accent transition-all duration-700" 
                                style={{ width: `${subStage.prob}%` }} 
                              />
                           </div>
                           <span className="text-[9px] font-black text-gray-400 tabular-nums">{subStage.prob}%</span>
                        </div>
                      )}
                    </div>

                    {isAdmin && (
                      <div className="flex items-center gap-0 border-l border-border/50 pl-1 ml-1 overflow-hidden w-0 group-hover:w-[56px] opacity-0 group-hover:opacity-100 transition-all duration-300">
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          title="Edit sub stage"
                          className="size-7 rounded-lg text-gray-400 hover:text-accent hover:bg-accent/5"
                          onClick={() => onEditSubStage?.(row, subStage)}
                        >
                          <Edit2 size={11} />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          title="Delete sub stage"
                          className="size-7 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50"
                          onClick={() => onDeleteSubStage?.(row, subStage)}
                        >
                          <Trash2 size={11} />
                        </Button>
                      </div>
                    )}
                  </div>
                ))
            ) : (
                <div className="w-full flex items-center gap-3 py-2.5 px-4 rounded-[16px] border border-dashed border-border/60 bg-gray-50/40">
                   <div className="size-2 rounded-full bg-gray-300 animate-pulse shrink-0" />
                   <div className="min-w-0">
                    <p className="text-[11px] font-bold text-gray-500 font-['Lexend_Deca'] truncate">No sub stages defined</p>
                    <p className="text-[10px] text-gray-400 truncate">Configure sub-flows for this stage to track granular progress.</p>
                   </div>
                </div>
            )}
          </div>
        </div>
      );
    },
    [getSubStages, isAdmin, onAddSubStage, onDeleteSubStage, onEditSubStage],
  );

  const renderStageNameWithToggle = (row: PipelineStageRow, displayStageName: string) => {
    const subStages = getSubStages?.(row) ?? [];
    const isExpanded = expandedRows.has(row.id);
    const hasSubStages = subStages.length > 0;

    return (
      <div className="min-w-0">
        <div className="flex items-center gap-2">
          <span className="block truncate max-w-[280px] text-[15px] font-bold tracking-tight text-gray-900 font-['Lexend'] md:max-w-none">
            {displayStageName}
          </span>
          {(hasSubStages || isAdmin) && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => toggleRow(row.id)}
              className={cn(
                "h-6 rounded-lg px-2 text-[10.5px] font-black font-['Lexend_Deca'] transition-all gap-1.5 flex items-center shrink-0",
                isExpanded 
                  ? "bg-accent/10 text-accent ring-1 ring-accent/20" 
                  : "bg-gray-100 text-gray-500 hover:bg-gray-200"
              )}
            >
              {isExpanded ? <ChevronDown size={12} className="stroke-[3px]" /> : <ChevronRight size={12} className="stroke-[3px]" />}
              {isExpanded ? "HIDE STAGES" : hasSubStages ? `VIEW SUB STAGES (${subStages.length})` : "ADD SUB STAGES"}
            </Button>
          )}
        </div>
        {isExpanded && renderSubStages(row)}
      </div>
    );
  };

  return (
    <>
      <div className="flex-1 min-h-0 overflow-auto custom-scrollbar">
        <div className="min-w-full inline-block align-middle">
          <Table variant="transparent">
            <TableHeader>
              <TableRow className="bg-gray-100/50 border-b border-border/60 hover:bg-gray-100/50 whitespace-nowrap">
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] w-[70px] text-center border-r border-border/50">
                  #
                </TableHead>
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] px-4 min-w-[300px]">
                  Stage / Task Details
                </TableHead>
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] px-4 w-[200px]">
                  Pipeline
                </TableHead>
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] px-4 w-[100px]">
                  Type
                </TableHead>
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] px-4 w-[100px]">
                  Created
                </TableHead>
                <TableHead className="text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] px-4 w-[100px]">
                   Updated
                </TableHead>
                <TableHead className="w-[120px] text-right text-[11px] font-black uppercase tracking-widest text-gray-400 font-['Lexend_Deca'] pr-6">
                  Control
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {groups ? (
                groups.map((group) => (
                  <React.Fragment key={group.stageNameId ?? group.stageName}>
                    <TableRow className="bg-accent/[0.03] hover:bg-accent/[0.03] border-b border-border/40">
                      <TableCell
                        colSpan={7}
                        className="bg-accent/[0.02] py-2.5 px-4 md:px-6"
                      >
                        <div className="flex items-center gap-2">
                          <div className="h-4 w-1 rounded-full bg-accent" />
                          <span className="text-[12px] font-black uppercase tracking-widest text-accent font-['Lexend_Deca']">
                            {group.stageName}
                          </span>
                          <span className="ml-1 rounded-md bg-gray-100 px-1.5 py-0.5 text-[10px] font-bold text-gray-400 tabular-nums">
                            {group.stages.length}
                          </span>
                        </div>
                      </TableCell>
                    </TableRow>
                    {group.stages.map((row) => {
                      const rowWithGroupName = {
                        ...row,
                        stageName: group.stageName,
                      };

                      return (
                        <TableRow
                          key={row.id}
                          className="group border-b border-border/60 transition-colors hover:bg-accent/[0.02]"
                        >
                          <TableCell className="py-3 text-center tabular-nums text-[13.5px] font-bold text-gray-400 transition-colors group-hover:text-accent border-r border-border/50">
                            {row.sortOrder + 1}
                          </TableCell>
                          <TableCell className="py-3 px-4 align-top">
                            {renderStageNameWithToggle(rowWithGroupName, rowWithGroupName.stageName)}
                          </TableCell>
                          <TableCell className="py-3 px-4">
                            <div className="flex min-w-0 items-center gap-2.5">
                              <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-accent/5 text-accent/60 shadow-sm transition-all group-hover:bg-accent/10 group-hover:text-accent">
                                <GitBranch size={13} className="stroke-[2.5px]" />
                              </div>
                              <span className="max-w-[120px] truncate text-[13.5px] font-semibold text-gray-700 font-['Lexend_Deca'] md:max-w-none">
                                {row.pipelineName}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell className="py-3 px-4">
                            <span
                              className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-black uppercase tracking-wider font-['Lexend_Deca'] ${
                                (row.stageType ?? "Lead") === "Deal"
                                  ? "bg-violet-100 text-violet-800"
                                  : "bg-emerald-100 text-emerald-800"
                              }`}
                            >
                              {row.stageType ?? "Lead"}
                            </span>
                          </TableCell>
                          <TableCell className="py-3 px-4 border-l border-border/10">
                            <span className="text-[11.5px] font-bold text-gray-700 tabular-nums">
                              {new Date(row.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                            </span>
                          </TableCell>
                          <TableCell className="py-3 px-4 border-l border-border/10">
                            <span className="text-[11.5px] font-bold text-gray-700 tabular-nums">
                              {new Date(row.updatedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                            </span>
                          </TableCell>
                          <TableCell className="py-2 text-right pr-4 md:pr-8">
                            {isAdmin && (
                              <div className="flex translate-x-0 items-center justify-end gap-1 opacity-100 transition-all duration-300 sm:gap-1.5">
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  className="h-8 w-8 md:h-9 md:w-9 rounded-xl text-gray-400 transition-all hover:bg-accent/5 hover:text-accent active:scale-95"
                                  onClick={() => onEdit(rowWithGroupName)}
                                >
                                  <Edit2 size={14} className="md:size-4" />
                                </Button>
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  className="h-8 w-8 md:h-9 md:w-9 rounded-xl text-gray-400 transition-all hover:bg-red-50 hover:text-red-500 active:scale-95"
                                  onClick={() => onDelete(row.id)}
                                >
                                  <Trash2 size={14} className="md:size-4" />
                                </Button>
                              </div>
                            )}
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </React.Fragment>
                ))
              ) : (
                rows?.map((row) => (
                  <TableRow
                    key={row.id}
                    className="group border-b border-border/60 transition-colors hover:bg-accent/[0.02]"
                  >
                    <TableCell className="py-3 text-center tabular-nums text-[13.5px] font-bold text-gray-400 transition-colors group-hover:text-accent border-r border-border/50">
                      {row.sortOrder + 1}
                    </TableCell>
                    <TableCell className="py-3 px-4 align-top">
                      {renderStageNameWithToggle(row, row.stageName)}
                    </TableCell>
                    <TableCell className="py-3 px-4">
                      <div className="flex min-w-0 items-center gap-2.5">
                        <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-accent/5 text-accent/60 shadow-sm transition-all group-hover:bg-accent/10 group-hover:text-accent">
                          <GitBranch size={13} className="stroke-[2.5px]" />
                        </div>
                        <span className="max-w-[120px] truncate text-[13.5px] font-semibold text-gray-700 font-['Lexend_Deca'] md:max-w-none">
                          {row.pipelineName}
                        </span>
                      </div>
                    </TableCell>
                    <TableCell className="py-3 px-4">
                      <span
                        className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-black uppercase tracking-wider font-['Lexend_Deca'] ${
                          (row.stageType ?? "Lead") === "Deal"
                            ? "bg-violet-100 text-violet-800"
                            : "bg-emerald-100 text-emerald-800"
                        }`}
                      >
                        {row.stageType ?? "Lead"}
                      </span>
                    </TableCell>
                    <TableCell className="py-3 px-4 border-l border-border/10">
                      <span className="text-[11.5px] font-bold text-gray-700 tabular-nums">
                        {new Date(row.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                      </span>
                    </TableCell>
                    <TableCell className="py-3 px-4 border-l border-border/10">
                      <span className="text-[11.5px] font-bold text-gray-700 tabular-nums">
                        {new Date(row.updatedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                      </span>
                    </TableCell>
                    <TableCell className="py-2 text-right pr-4 md:pr-8">
                      {isAdmin && (
                        <div className="flex translate-x-0 items-center justify-end gap-1 opacity-100 transition-all duration-300 sm:gap-1.5">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 md:h-9 md:w-9 rounded-xl text-gray-400 transition-all hover:bg-accent/5 hover:text-accent active:scale-95"
                            onClick={() => onEdit(row)}
                          >
                            <Edit2 size={14} className="md:size-4" />
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 md:h-9 md:w-9 rounded-xl text-gray-400 transition-all hover:bg-red-50 hover:text-red-500 active:scale-95"
                            onClick={() => onDelete(row.id)}
                          >
                            <Trash2 size={14} className="md:size-4" />
                          </Button>
                        </div>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      <div className="flex shrink-0 flex-col items-center justify-between gap-4 border-t border-border/50 bg-gray-50/30 px-6 py-4 sm:flex-row">
        <p className="text-[12px] font-bold tracking-tight text-gray-500 font-['Lexend_Deca']">
          Showing <span className="text-gray-900">{total}</span> of{" "}
          <span className="text-gray-900">{total}</span> stages
        </p>
        <div className="flex items-center gap-3">
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="h-9 w-9 rounded-2xl border-border/60 p-0 shadow-sm hover:border-accent/40 hover:bg-white"
            disabled={page <= 1}
            onClick={() => onPageChange(Math.max(1, page - 1))}
          >
            <ChevronLeft size={18} />
          </Button>
          <div className="flex h-9 min-w-[70px] items-center justify-center rounded-2xl border border-border/60 bg-white px-4 text-[12px] font-bold text-gray-700 shadow-sm font-['Lexend_Deca']">
            {page} / {totalPages}
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="h-9 w-9 rounded-2xl border-border/60 p-0 shadow-sm hover:border-accent/40 hover:bg-white"
            disabled={page >= totalPages}
            onClick={() => onPageChange(Math.min(totalPages, page + 1))}
          >
            <ChevronRight size={18} />
          </Button>
        </div>
      </div>
    </>
  );
}
