import { Button, Checkbox, TableCell, TableRow, Tooltip, TooltipContent, TooltipTrigger } from "@repo/shadcn-ui/components";
import { cn } from '@repo/shadcn-ui/lib/utils';
import { ArrowDownIcon, ArrowUpIcon, CopyIcon, Trash2Icon } from "lucide-react";
import { Control, Controller, FieldValues } from "react-hook-form";
import { useInvoiceContext } from '../../../context';
import { useTranslation } from '../../../i18n';
import { CustomerInvoiceTaxesMultiSelect } from '../../customer-invoice-taxes-multi-select';
import { AmountInputField } from './amount-input-field';
import { HoverCardTotalsSummary } from './hover-card-total-summary';
import { PercentageInputField } from './percentage-input-field';
import { QuantityInputField } from './quantity-input-field';

export type ItemRowProps<TFieldValues extends FieldValues = FieldValues> = {

    control: Control<TFieldValues>,
    rowIndex: number;
    isSelected: boolean;
    isFirst: boolean;
    isLast: boolean;
    readOnly: boolean;
    onToggleSelect: () => void;
    onDuplicate: () => void;
    onMoveUp: () => void;
    onMoveDown: () => void;
    onRemove: () => void;
}


export const ItemRow = <TFieldValues extends FieldValues = FieldValues>({
    control,
    rowIndex,
    isSelected,
    isFirst,
    isLast,
    readOnly,
    onToggleSelect,
    onDuplicate,
    onMoveUp,
    onMoveDown,
    onRemove, }: ItemRowProps<TFieldValues>) => {
    const { t } = useTranslation();
    const { currency_code, language_code } = useInvoiceContext();

    return (
        <TableRow data-row-index={rowIndex}>
            {/* selección */}
            <TableCell className='align-top' data-col-index={1}>
                <div className='h-5'>
                    <Checkbox
                        aria-label={`Seleccionar fila ${rowIndex + 1}`}
                        className="block size-5 leading-none align-middle"
                        checked={isSelected}
                        onCheckedChange={onToggleSelect}
                        disabled={readOnly}
                        data-cell-focus
                    />
                </div>
            </TableCell>

            {/* # */}
            <TableCell className='text-left pt-[6px]' data-col-index={2}>
                <span className='block translate-y-[-1px] text-muted-foreground tabular-nums text-xs'>
                    {rowIndex + 1}
                </span>
            </TableCell>

            {/* description */}
            <TableCell data-col-index={3}>
                <Controller
                    control={control}
                    name={`items.${rowIndex}.description`}
                    render={({ field }) => (
                        <textarea
                            {...field}
                            aria-label={t("form_fields.item.description.label")}
                            className={cn(
                                "w-full bg-transparent p-0 pt-1.5 resize-none border-0 shadow-none h-8",
                                "hover:bg-background hover:border-ring hover:ring-ring/50 hover:ring-[2px] focus-within:resize-y",
                            )}
                            rows={1}
                            spellCheck
                            readOnly={readOnly}
                            onFocus={(e) => {
                                const el = e.currentTarget;
                                el.style.height = "auto";
                                el.style.height = `${el.scrollHeight}px`;
                            }}
                            data-cell-focus
                        />
                    )}
                />
            </TableCell>

            {/* qty */}
            <TableCell className='text-right' data-col-index={4}>
                <QuantityInputField
                    control={control}
                    name={`items.${rowIndex}.quantity`}
                    readOnly={readOnly}
                    inputId={`quantity-${rowIndex}`}
                    emptyMode="blank"
                    data-row-index={rowIndex}
                    data-col-index={4}
                    data-cell-focus
                    className='font-medium'
                />
            </TableCell>

            {/* unit */}
            <TableCell className='text-right' data-col-index={5}>
                <AmountInputField
                    control={control}
                    name={`items.${rowIndex}.unit_amount`}
                    readOnly={readOnly}
                    inputId={`unit-amount-${rowIndex}`}
                    scale={4}
                    currencyCode={currency_code}
                    languageCode={language_code}
                    data-row-index={rowIndex}
                    data-col-index={5}
                    data-cell-focus
                    className='font-medium'
                />
            </TableCell>

            {/* discount */}
            <TableCell className='text-right' data-col-index={6}>
                <PercentageInputField
                    control={control}
                    name={`items.${rowIndex}.discount_percentage`}
                    readOnly={readOnly}
                    inputId={`discount-percentage-${rowIndex}`}
                    showSuffix
                    data-row-index={rowIndex}
                    data-col-index={6}
                    data-cell-focus
                    className='font-medium'
                />
            </TableCell>

            {/* taxes */}
            <TableCell data-col-index={7}>
                <Controller
                    control={control}
                    name={`items.${rowIndex}.tax_codes`}
                    render={({ field }) => (
                        <CustomerInvoiceTaxesMultiSelect
                            value={field.value}
                            onChange={field.onChange}
                            data-row-index={rowIndex}
                            data-col-index={7}
                        />
                    )}
                    data-cell-focus
                />
            </TableCell>

            {/* total (solo lectura) */}
            <TableCell className='text-right tabular-nums pt-[6px] leading-5' data-col-index={8}>
                <HoverCardTotalsSummary rowIndex={rowIndex} >
                    <AmountInputField
                        control={control}
                        name={`items.${rowIndex}.total_amount`}
                        readOnly
                        inputId={`total-amount-${rowIndex}`}
                        currencyCode={currency_code}
                        languageCode={language_code}
                        className='font-semibold'
                    />
                </HoverCardTotalsSummary>
            </TableCell>

            {/* actions */}
            <TableCell className='pt-[4px]' data-col-index={9}>
                <div className='flex justify-end gap-0'>
                    {onDuplicate && (
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    size='icon'
                                    variant='ghost'
                                    onMouseDown={(e) => e.preventDefault()}
                                    onClick={onDuplicate}
                                    disabled={readOnly}
                                    aria-label='Duplicar fila'
                                    className='size-8 self-start -translate-y-[1px]'
                                    data-cell-focus
                                >
                                    <CopyIcon className='size-4' />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>Duplicar</TooltipContent>
                        </Tooltip>
                    )}

                    {onMoveUp && (
                        <Button
                            size='icon'
                            variant='ghost'
                            onMouseDown={(e) => e.preventDefault()}
                            onClick={onMoveUp}
                            disabled={readOnly || isFirst}
                            aria-label='Mover arriba'
                            className='size-8 self-start -translate-y-[1px]'
                            data-cell-focus
                        >
                            <ArrowUpIcon className='size-4' />
                        </Button>
                    )}

                    {onMoveDown && (
                        <Button
                            size='icon'
                            variant='ghost'
                            onMouseDown={(e) => e.preventDefault()}
                            onClick={onMoveDown}
                            disabled={readOnly || isLast}
                            aria-label='Mover abajo'
                            className='size-8 self-start -translate-y-[1px]'
                            data-cell-focus
                        >
                            <ArrowDownIcon className='size-4' />
                        </Button>
                    )}

                    {onRemove && (
                        <Button
                            size='icon'
                            variant='ghost'
                            onMouseDown={(e) => e.preventDefault()}
                            onClick={onRemove}
                            disabled={readOnly}
                            aria-label='Eliminar fila'
                            className='size-8 self-start -translate-y-[1px]'
                            data-cell-focus
                        >
                            <Trash2Icon className='size-4' />
                        </Button>
                    )}
                </div>
            </TableCell>
        </TableRow>
    );
}