'use client';

import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';

import { Badge } from '@/components/ui/badge';
import type { Plan } from '@/types';

function formatDate(value?: string | null) {
  if (!value) return '-';
  return new Intl.DateTimeFormat('en-IN', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  }).format(new Date(value));
}

function formatPrice(value: string, cycle: string) {
  const amount = Number(value);
  const price = Number.isFinite(amount) ? amount.toFixed(2) : value;
  return `${price} / ${cycle}`;
}

export function usePlanColumns(): ColumnDef<Plan>[] {
  return useMemo(() => {
    return [
      {
        accessorKey: 'name',
        header: 'Plan',
        cell: ({ row }) => (
          <div>
            <p>{row.original.name}</p>
            <p className="text-muted-foreground">{row.original.slug}</p>
          </div>
        ),
      },
      {
        accessorKey: 'price',
        header: 'Price',
        cell: ({ row }) =>
          formatPrice(row.original.price, row.original.billing_cycle),
      },
      {
        accessorKey: 'trial_days',
        header: 'Trial',
        cell: ({ row }) => `${row.original.trial_days} days`,
      },
      {
        id: 'limits',
        header: 'Limits',
        enableSorting: false,
        cell: ({ row }) => (
          <div className="text-muted-foreground">
            <p>{row.original.max_projects} projects</p>
            <p>{row.original.max_users} users</p>
          </div>
        ),
      },
      {
        accessorKey: 'created_at',
        header: 'Created',
        cell: ({ row }) => formatDate(row.original.created_at),
      },
      {
        accessorKey: 'is_active',
        header: 'Status',
        cell: ({ row }) => (
          <div className="flex flex-wrap gap-1.5">
            <Badge variant={row.original.is_active ? 'default' : 'secondary'}>
              {row.original.is_active ? 'Active' : 'Inactive'}
            </Badge>
            {row.original.is_custom ? (
              <Badge variant="outline">Custom</Badge>
            ) : null}
          </div>
        ),
      },
    ];
  }, []);
}
