"use client";

import * as React from "react";
import { ChevronDown, ChevronRight, Target, Edit } from "lucide-react";
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { snakeCaseToTitleCase } from "@/lib/utils";
import { useEditEpicModal } from "@/features/epics/hooks/use-edit-epic-modal";

interface DataTableEpicGroupedProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
}

interface GroupedData {
  epicId: string | null;
  epicName: string | null;
  epicStatus?: string;
  tasks: any[];
  stats?: {
    totalTasks: number;
    completedTasks: number;
    progressPercentage: number;
  };
}

export function DataTableEpicGrouped<TData, TValue>({
  columns,
  data,
}: DataTableEpicGroupedProps<TData, TValue>) {
  const { open: openEditEpicModal } = useEditEpicModal();

  // Group tasks by epic
  const groupedData = React.useMemo(() => {
    const groups: { [key: string]: GroupedData } = {};
    
    (data as any[]).forEach((task) => {
      const epicKey = task.epic?.id || 'no-epic';
      
      if (!groups[epicKey]) {
        groups[epicKey] = {
          epicId: task.epic?.id || null,
          epicName: task.epic?.name || null,
          epicStatus: task.epic?.status,
          tasks: [],
          stats: undefined,
        };
      }
      
      groups[epicKey].tasks.push(task);
    });

    // Calculate stats for each epic
    Object.values(groups).forEach((group) => {
      if (group.epicId) {
        const totalTasks = group.tasks.length;
        const completedTasks = group.tasks.filter((task: any) => task.status === "DONE").length;
        
        group.stats = {
          totalTasks,
          completedTasks,
          progressPercentage: totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0,
        };
      }
    });

    return Object.values(groups).sort((a, b) => {
      // Sort: epics first (alphabetically), then "no epic" tasks
      if (!a.epicId && !b.epicId) return 0;
      if (!a.epicId) return 1;
      if (!b.epicId) return -1;
      return (a.epicName || '').localeCompare(b.epicName || '');
    });
  }, [data]);

  const [expandedGroups, setExpandedGroups] = React.useState<Set<string>>(
    new Set(groupedData.map((group) => group.epicId || 'no-epic'))
  );

  const toggleGroup = (groupKey: string) => {
    const newExpanded = new Set(expandedGroups);
    if (newExpanded.has(groupKey)) {
      newExpanded.delete(groupKey);
    } else {
      newExpanded.add(groupKey);
    }
    setExpandedGroups(newExpanded);
  };

  const handleEditEpic = (epicId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    openEditEpicModal(epicId);
  };

  const table = useReactTable({
    data: [],
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <div>
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              {table.getHeaderGroups()[0]?.headers.map((header) => (
                <TableHead key={header.id}>
                  {header.isPlaceholder
                    ? null
                    : flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {groupedData.length ? (
              groupedData.map((group) => {
                const groupKey = group.epicId || 'no-epic';
                const isExpanded = expandedGroups.has(groupKey);
                
                return (
                  <React.Fragment key={groupKey}>
                    {/* Epic Header Row (only for tasks with epics) */}
                    {group.epicId && (
                      <TableRow className="bg-muted/50 hover:bg-muted/70 border-b-2 cursor-pointer">
                        <TableCell colSpan={columns.length} className="py-3">
                          <div className="flex items-center gap-3 w-full" onClick={() => toggleGroup(groupKey)}>
                            {isExpanded ? (
                              <ChevronDown className="h-4 w-4" />
                            ) : (
                              <ChevronRight className="h-4 w-4" />
                            )}
                            <Target className="h-4 w-4 text-purple-600" />
                            <span className="text-base font-semibold">{group.epicName}</span>
                            
                            <div className="flex items-center gap-2 ml-auto">
                              {/* {group.epicStatus && (
                                <Badge variant={group.epicStatus as any} className="text-xs">
                                  {snakeCaseToTitleCase(group.epicStatus)}
                                </Badge>
                              )} */}
                              {group.stats && (
                                <Badge variant="outline" className="text-xs">
                                  {group.stats.completedTasks}/{group.stats.totalTasks} tasks
                                </Badge>
                              )}
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0 opacity-70 hover:opacity-100"
                                onClick={(e) => handleEditEpic(group.epicId!, e)}
                                title="Edit Epic"
                              >
                                <Edit className="h-3 w-3" />
                              </Button>
                            </div>
                          </div>
                        </TableCell>
                      </TableRow>
                    )}
                    
                    {/* Task Rows */}
                    {(!group.epicId || isExpanded) && group.tasks.map((task, index) => (
                      <TableRow key={`${groupKey}-${task.id}`} className={group.epicId ? "bg-background/50" : ""}>
                        {columns.map((column, colIndex) => (
                          <TableCell 
                            key={`${task.id}-${colIndex}`}
                            className={group.epicId ? "pl-8" : ""}
                          >
                            {flexRender(
                              column.cell,
                              {
                                row: {
                                  original: task,
                                  getValue: (key: string) => task[key],
                                },
                                column,
                                table,
                              } as any
                            )}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))}
                  </React.Fragment>
                );
              })
            ) : (
              <TableRow>
                <TableCell colSpan={columns.length} className="h-24 text-center">
                  No results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
} 