'use client';

/* IMPORT */
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { CircleCheckBig, CircleX, Ellipsis, Handshake, OctagonAlert } from 'lucide-react';
import { DataTableColumnHeaderSimple } from '@/components/data-table/data-table-column-simple-header';
import { Dispatch, SetStateAction } from 'react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  RISK_RATING_CASHFLOW_LIST,
  RISK_RATING_CREDIT_LIST,
  RISK_RATING_TOTAL_LIST,
  RISK_RATING_WATCH_LIST
} from '@/config/risksConfig';
import { type AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime';
import { type ColumnDef } from '@tanstack/react-table';
import { type DataTableRowAction } from '@/types/table';
import { type RisksView } from '@/db/schema';

// ----------------------------------------------------------------------------------------------------

/* TYPES */
interface GetColumnsProps {
  setRowAction: Dispatch<SetStateAction<DataTableRowAction<RisksView> | null>>;
  router: AppRouterInstance;
  paramsLanguage: string;
};

// ----------------------------------------------------------------------------------------------------

/* FUNCTION FOR GETTING COLUMNS SETTING */
function getColumns(props: GetColumnsProps): ColumnDef<RisksView>[] {
  const { setRowAction, router, paramsLanguage } = props;

  // [1] SELECT COLUMN - CHECKBOX
  const selectColumn: ColumnDef<RisksView> = {
    id: 'select',
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && 'indeterminate')
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="select-all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="select-row"
        className="translate-y-0.5"
      />
    ),
    enableSorting: false,
    enableHiding: false,
  };

  // [2] SOURCE COLUMNS
  const sourceColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'eventType',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="항목" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('eventType');
        return (
          <Badge variant="default">
            {value}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Risk Category',
        group: 'Risk Information',
        type: 'select',
      },
    },
    {
      accessorKey: 'vendorCode',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체 코드" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('vendorCode');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Vendor Code',
        group: 'Risk Information',
        type: 'text',
      },
    },
    {
      accessorKey: 'vendorName',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체명" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('vendorName');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Vendor Name',
        group: 'Risk Information',
        type: 'text',
      },
    },
    {
      accessorKey: 'businessNumber',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="사업자등록번호" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('businessNumber');
        const digits = value.replace(/\D/g, '');
        const formattedValue = digits.length === 10
          ? `${digits.slice(0, 3)}-${digits.slice(3, 5)}-${digits.slice(5)}`
          : value;
        return (
          <div className="font-regular">
            {formattedValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Business Number',
        group: 'Risk Information',
        type: 'text',
      },
    },
    {
      accessorKey: 'provider',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="신용평가사" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('provider');
        return (
          <Badge variant="secondary">
            {value}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Provider',
        group: 'Risk Information',
        type: 'text',
      },
    },
    {
      accessorKey: 'content',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="상세 내용" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('content');
        return (
          <div className="font-regular max-w-[150px] truncate" title={value}>
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Risk Content',
        group: 'Risk Information',
        type: 'text',
      },
    },
    {
      accessorKey: 'occuredAt',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="발생일시" />
      ),
      cell: ({ row }) => {
        const date = row.getValue<Date>('occuredAt');
        return (
          <div className="font-regular">
            {date ? new Date(date).toLocaleDateString('ko-KR') : '-'}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Occured At',
        group: 'Risk Information',
        type: 'date',
      },
    },
  ];

  // [3] TOTAL RATING COLUMNS
  const ratingTotalColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'prevRatingTotal',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="이전" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('prevRatingTotal');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Previous',
        group: 'Total Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'curRatingTotal',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="현재" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('curRatingTotal');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Current',
        group: 'Total Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'changeRatingTotal',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="변동" />
      ),
      cell: ({ row }) => {
        const prevValue = row.getValue<string>('prevRatingTotal');
        const curValue = row.getValue<string>('curRatingTotal');

        if (prevValue === '-' || curValue === '-' || !prevValue || !curValue) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        }
        const prevRating = RISK_RATING_TOTAL_LIST.find(rating => rating.label === prevValue);
        const curRating = RISK_RATING_TOTAL_LIST.find(rating => rating.label === curValue);

        if (!prevRating || !curRating || prevRating === curRating) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        } else if (prevRating.value > curRating.value) {
          return (
            <div className="font-regular text-red-500">
              ▲
            </div>
          );
        } else {
          return (
            <div className="font-regular text-blue-500">
              ▼
            </div>
          );
        }
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Change',
        group: 'Total Rating',
        type: 'text',
      },
    },
  ];

  // [4] CREDIT RATING COLUMNS
  const ratingCreditColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'prevRatingCredit',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="이전" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('prevRatingCredit');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Previous',
        group: 'Credit Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'curRatingCredit',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="현재" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('curRatingCredit');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Current',
        group: 'Credit Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'changeRatingCredit',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="변동" />
      ),
      cell: ({ row }) => {
        const prevValue = row.getValue<string>('prevRatingCredit');
        const curValue = row.getValue<string>('curRatingCredit');

        if (prevValue === '-' || curValue === '-' || !prevValue || !curValue) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        }
        const prevRating = RISK_RATING_CREDIT_LIST.find(rating => rating.label === prevValue);
        const curRating = RISK_RATING_CREDIT_LIST.find(rating => rating.label === curValue);

        if (!prevRating || !curRating || prevRating === curRating) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        } else if (prevRating.value > curRating.value) {
          return (
            <div className="font-regular text-red-500">
              ▲
            </div>
          );
        } else {
          return (
            <div className="font-regular text-blue-500">
              ▼
            </div>
          );
        }
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Change',
        group: 'Credit Rating',
        type: 'text',
      },
    },
  ];

  // [5] CASHFLOW RATING COLUMNS
  const ratingCashflowColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'prevRatingCashflow',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="이전" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('prevRatingCashflow');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Previous',
        group: 'Cashflow Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'curRatingCashflow',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="현재" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('curRatingCashflow');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Current',
        group: 'Cashflow Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'changeRatingCashflow',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="변동" />
      ),
      cell: ({ row }) => {
        const prevValue = row.getValue<string>('prevRatingCashflow');
        const curValue = row.getValue<string>('curRatingCashflow');

        if (prevValue === '-' || curValue === '-' || !prevValue || !curValue) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        }
        const prevRating = RISK_RATING_CASHFLOW_LIST.find(rating => rating.label === prevValue);
        const curRating = RISK_RATING_CASHFLOW_LIST.find(rating => rating.label === curValue);

        if (!prevRating || !curRating || prevRating === curRating) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        } else if (prevRating.value > curRating.value) {
          return (
            <div className="font-regular text-red-500">
              ▲
            </div>
          );
        } else {
          return (
            <div className="font-regular text-blue-500">
              ▼
            </div>
          );
        }
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Change',
        group: 'Cashflow Rating',
        type: 'text',
      },
    },
  ];

  // [6] WATCH RATING COLUMNS
  const ratingWatchColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'prevRatingWatch',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="이전" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('prevRatingWatch');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Previous',
        group: 'Watch Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'curRatingWatch',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="현재" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('curRatingWatch');
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Current',
        group: 'Watch Rating',
        type: 'text',
      },
    },
    {
      accessorKey: 'changeRatingWatch',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="변동" />
      ),
      cell: ({ row }) => {
        const prevValue = row.getValue<string>('prevRatingWatch');
        const curValue = row.getValue<string>('curRatingWatch');

        if (prevValue === '-' || curValue === '-' || !prevValue || !curValue) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        }
        const prevRating = RISK_RATING_WATCH_LIST.find(rating => rating.label === prevValue);
        const curRating = RISK_RATING_WATCH_LIST.find(rating => rating.label === curValue);

        if (!prevRating || !curRating || prevRating === curRating) {
          return (
            <div className="font-regular">
              -
            </div>
          );
        } else if (prevRating.value > curRating.value) {
          return (
            <div className="font-regular text-red-500">
              ▲
            </div>
          );
        } else {
          return (
            <div className="font-regular text-blue-500">
              ▼
            </div>
          );
        }
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Change',
        group: 'Watch Rating',
        type: 'text',
      },
    },
  ];

  // [7] INPUT COLUMNS
  const inputColumns: ColumnDef<RisksView>[] = [
    {
      accessorKey: 'eventStatus',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="리스크 해소 여부" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<boolean>('eventStatus');

        if (value) {
          return (
            <div className="flex items-center gap-2 text-destructive font-bold">
              <CircleX size={20} strokeWidth={2} />
              아니오
            </div>
          );
        }
        return (
          <div className="flex items-center gap-2 text-primary font-bold">
            <CircleCheckBig size={20} strokeWidth={2} />
            예
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Risk Not Cleared',
        group: 'Risk Management',
        type: 'text',
      },
    },
    {
      accessorKey: 'managerName',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="구매 담당자" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('managerName') ?? '-';
        return (
          <div className="font-regular">
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Procurement Manager Name',
        group: 'Risk Management',
        type: 'text',
      },
    },
    {
      accessorKey: 'adminComment',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="관리 담당자 의견" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('adminComment') ?? '-';
        return (
          <div className="font-regular max-w-[150px] truncate" title={value}>
            {value}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Risk Manager Comment',
        group: 'Risk Management',
        type: 'text',
      },
    },
  ];

  // [8] ACTIONS COLUMN - DROPDOWN MENU WITH VIEW ACTION
  const actionsColumn: ColumnDef<RisksView> = {
    id: 'actions',
    enableHiding: false,
    cell: function Cell({ row }) {
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="Open menu"
              variant="ghost"
              className="flex size-8 p-0 data-[state=open]:bg-muted"
            >
              <Ellipsis className="size-4" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-60">
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "update" })}
              className="cursor-pointer"
            >
              <OctagonAlert className="mr-2 size-4" />
              리스크 관리
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => {
                const vendorId = row.original.vendorId;
                router.push(`/${paramsLanguage}/evcp/vendors/${vendorId}/info/credit`);
              }}
              className="cursor-pointer"
            >
              <Handshake className="mr-2 size-4" />
              신용정보 확인
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
  };

  return [
    selectColumn,
    {
      id: 'riskSource',
      header: '리스크 정보',
      columns: sourceColumns,
    },
    {
      id: 'ratingTotal',
      header: '종합등급',
      columns: ratingTotalColumns,
    },
    {
      id: 'ratingCredit',
      header: '신용등급',
      columns: ratingCreditColumns,
    },
    {
      id: 'ratingCashflow',
      header: '현금흐름등급',
      columns: ratingCashflowColumns,
    },
    {
      id: 'ratingWatch',
      header: 'WATCH등급',
      columns: ratingWatchColumns,
    },
    {
      id: 'riskInput',
      header: '리스크 관리',
      columns: inputColumns,
    },
    actionsColumn,
  ];
};

// ----------------------------------------------------------------------------------------------------

/* EXPORT */
export default getColumns;