import DataTable from '@/components/common/data-table';
import PageHeading from '@/components/common/page-heading';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import { TMarketPosition } from '@/types/market.types';
import { router } from '@inertiajs/react';
import { CaretRightIcon } from '@phosphor-icons/react';
import { SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

const Portfolio = () => {
  const { t } = useTranslation();
  const { format } = useCurrency();
  const [sorting, setSorting] = useState<SortingState>([]);

  const { data: positions, isLoading } =
    useApiSWR<TMarketPosition[]>('/user/portfolio');

  return (
    <>
      <PageHeading
        title={t('My Portfolio')}
        description={t('Your active and settled positions.')}
        variant="default"
      />

      <Card className="p-0">
        <DataTable
          data={positions ?? []}
          sorting={sorting}
          setSorting={setSorting}
          isLoading={isLoading}
          rounded={false}
          shadow={false}
          structure={[
            {
              accessorKey: 'market',
              header: t('Market'),
              cell: ({ row }) => (
                <button
                  className="flex cursor-pointer items-center gap-1 text-left text-sm font-medium hover:underline"
                  onClick={() =>
                    router.visit(`/markets/${row.original.market.slug}`)
                  }
                >
                  <span className="line-clamp-2">
                    {row.original.market.title}
                  </span>
                  <CaretRightIcon weight="bold" className="size-3.5 shrink-0" />
                </button>
              ),
            },
            {
              accessorKey: 'outcome',
              header: t('Outcome'),
              cell: ({ row }) => {
                const o = row.original.outcome;
                return (
                  <Badge
                    variant="secondary"
                    style={
                      o.color
                        ? { backgroundColor: o.color + '20', color: o.color }
                        : {}
                    }
                  >
                    {o.title}
                  </Badge>
                );
              },
            },
            {
              accessorKey: 'shares',
              header: t('Shares'),
              cell: ({ row }) => Number(row.original.shares).toFixed(4),
            },
            {
              accessorKey: 'avg_price',
              header: t('Avg Price'),
              cell: ({ row }) => format(Number(row.original.avg_price)),
            },
            {
              accessorKey: 'current_value',
              header: t('Value'),
              cell: ({ row }) => format(row.original.current_value),
            },
            {
              accessorKey: 'unrealised_pnl',
              header: t('P&L'),
              cell: ({ row }) => {
                const pnl = row.original.unrealised_pnl;
                return (
                  <span
                    className={
                      pnl >= 0
                        ? 'text-green-600 dark:text-green-400'
                        : 'text-red-500'
                    }
                  >
                    {pnl >= 0 ? '+' : ''}
                    {format(pnl)}
                  </span>
                );
              },
            },
            {
              accessorKey: 'market.status',
              header: t('Status'),
              cell: ({ row }) => (
                <Badge
                  variant={
                    row.original.market.status === 'resolved'
                      ? 'successSubtle'
                      : row.original.market.status === 'open'
                        ? 'secondary'
                        : 'warning'
                  }
                  className="capitalize"
                >
                  {row.original.market.status}
                </Badge>
              ),
            },
          ]}
        />
      </Card>
    </>
  );
};

Portfolio.title = 'Portfolio';

export default Portfolio;
