import { ColumnDef } from '@tanstack/react-table';
import { ArrowUpDown, Star, StarHalf } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Review } from '@/types';
import { ScoreGrid } from './score-grid';
import { SourceBadge } from './source-badge';

const MAX_STARS = 5;

function StarRating({ rating }: { rating: number }) {
    const ratio = Math.min(1, Math.max(0, rating / MAX_STARS));
    const stars = Math.round(ratio * MAX_STARS * 2) / 2;
    const fullStars = Math.max(0, Math.floor(stars));
    const hasHalfStar = stars % 1 === 0.5;
    const emptyStars = Math.max(0, MAX_STARS - fullStars - (hasHalfStar ? 1 : 0));

    return (
        <div className="flex items-center gap-1">
            {[...Array(fullStars)].map((_, i) => (
                <Star key={`full-${i}`} className="h-4 w-4 text-yellow-500" fill="currentColor" stroke="none" />
            ))}
            {hasHalfStar && <StarHalf key="half" className="h-4 w-4 text-yellow-500" fill="currentColor" stroke="none" />}
            {[...Array(emptyStars)].map((_, i) => (
                <Star key={`empty-${i}`} className="h-4 w-4 text-gray-300" />
            ))}
            <span className="ml-2 text-sm">{rating.toFixed(2)}</span>
        </div>
    );
}

export const getColumns = (t: (namespace: string, key: string) => string): ColumnDef<Review>[] => [
    {
        accessorKey: 'guest_name',
        header: t('reviews', 'guest'),
        cell: ({ row }) => row.original.guest_name ?? '—',
    },
    {
        accessorKey: 'property_name',
        header: t('reviews', 'property'),
        cell: ({ row }) => {
            const { property_name, property_internal_name } = row.original;
            if (!property_name) {
                return <span className="text-gray-400">{row.original.property_id}</span>;
            }
            return (
                <span>
                    {property_name}
                    {property_internal_name && (
                        <span className="ml-1 text-xs text-gray-400">({property_internal_name})</span>
                    )}
                </span>
            );
        },
    },
    {
        accessorKey: 'source',
        header: t('reviews', 'source'),
        cell: ({ row }) => <SourceBadge source={row.original.source} />,
    },
    {
        accessorKey: 'rating',
        header: ({ column }) => (
            <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}>
                {t('reviews', 'rating')}
                <ArrowUpDown className="ml-2 h-4 w-4" />
            </Button>
        ),
        cell: ({ row }) => <StarRating rating={Number(row.original.rating) || 0} />,
    },
    {
        accessorKey: 'comment',
        header: t('reviews', 'comment'),
        cell: ({ row }) => {
            const { comment, score_details } = row.original;
            const hasComment = typeof comment === 'string' && comment.trim() !== '';
            const hasScores = score_details && Object.keys(score_details).length > 0;
            if (!hasComment && hasScores) {
                return <ScoreGrid scores={score_details} />;
            }
            return <p className="max-w-md whitespace-normal break-words text-sm">{comment}</p>;
        },
    },
    {
        accessorKey: 'ru_created_at',
        header: ({ column }) => (
            <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}>
                {t('reviews', 'created_at')}
                <ArrowUpDown className="ml-2 h-4 w-4" />
            </Button>
        ),
        cell: ({ row }) => row.original.ru_created_at ?? '—',
    },
];
