import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useTranslation } from '@/hooks/use-translation';
import { cn } from '@/lib/utils';
import { Check, ChevronsUpDown, PlusIcon, Trash2Icon } from 'lucide-react';
import React from 'react';
import { FEE_COLLECT_TIMES, FEE_DISCRIMINATORS_WITH_APPLIED_TO, MANDATORY_FEE_TYPES } from '../constants';
import type { AdditionalFee, FeeDiscriminator, FeeType } from '../types';

type AdditionalFeesEditorProps = {
    fees: AdditionalFee[];
    onChange: (next: AdditionalFee[]) => void;
    feeTypes: FeeType[];
    feeDiscriminators: FeeDiscriminator[];
    fieldErrors?: Record<string, string>;
};

export default function AdditionalFeesEditor({ fees, onChange, feeTypes, feeDiscriminators, fieldErrors = {} }: AdditionalFeesEditorProps) {
    const { t } = useTranslation();

    const handleAddAdditionalFee = () => {
        const newFee = {
            name: '',
            discriminatorId: '',
            typeId: '',
            amount: '',
            collectTime: FEE_COLLECT_TIMES.AT_BOOKING,
            optional: false,
            // order: '0',
        };
        onChange([...fees, newFee]);
    };

    const handleAdditionalFeeChange = (index: number, field: keyof AdditionalFee, value: string | number | boolean) => {
        const updatedFees = [...fees];
        updatedFees[index] = {
            ...updatedFees[index],
            [field]: value,
        };
        onChange(updatedFees);
    };

    const handleRemoveAdditionalFee = (index: number) => {
        const updatedFees = [...fees];
        updatedFees.splice(index, 1);
        onChange(updatedFees);
    };

    const [open] = React.useState(false);
    const listRef = React.useRef<HTMLDivElement>(null);

    return (
        <>
            <h2 className="mt-4 mb-1 text-lg font-bold">
                <span className="text-secondary mr-1">•</span>
                {t('properties.step5', 'additional_fees_title')}
            </h2>
            <p className="text-xs text-gray-500 sm:text-sm">
                {t('properties.step5', 'additional_fees_instruction')} <span className="text-red-500">*</span>
            </p>
            <div>
                <Button
                    type="button"
                    onClick={handleAddAdditionalFee}
                    variant={'outline'}
                    className="border-secondary text-secondary hover:text-primary mb-4 cursor-pointer border hover:bg-white"
                >
                    <PlusIcon className="mr-1 h-4 w-4" />
                    {t('properties.step5', 'add_fee_button')}
                </Button>
            </div>

            {fees.map((fee, index) => (
                <div key={index}>
                    <div
                        className={cn(
                            'flex items-center justify-between gap-3 rounded-sm border p-4',
                            fieldErrors['additional_fee_' + index] && 'border-red-500',
                        )}
                    >
                        <div>
                        <div className="mb-4 grid grid-cols-2 items-center gap-3">
                            <div className="flex flex-col gap-1">
                                <Label htmlFor={`fee_type_${index}`}>{t('properties.step5', 'fee_type')}</Label>
                                <Popover>
                                    <PopoverTrigger asChild>
                                        <Button
                                            variant="outline"
                                            role="combobox"
                                            aria-expanded={open}
                                            className={cn('w-full justify-between')}
                                        >
                                            {fee.typeId ? feeTypes.find((item) => item.id === fee.typeId)?.name : <span>{t('properties.step5', 'select_fee_type')}</span>}
                                            <ChevronsUpDown className="opacity-50" />
                                        </Button>
                                    </PopoverTrigger>
                                    <PopoverContent className="z-99 p-0">
                                        <Command>
                                            <CommandInput
                                                placeholder={t('properties.step5', 'search_fee_type')}
                                                onValueChange={() => {
                                                    if (listRef.current) {
                                                        listRef.current.scrollTop = 0;
                                                    }
                                                }}
                                                className="h-9"
                                            />
                                            <CommandList ref={listRef}>
                                                <CommandEmpty>
                                                    {t('properties.step5', 'no_fee_type_found')}
                                                </CommandEmpty>
                                                <CommandGroup>
                                                    {feeTypes.map((item) => (
                                                        <CommandItem
                                                            key={item.id}
                                                            value={item.name}
                                                            onSelect={() =>  handleAdditionalFeeChange(index, 'typeId', item.id)}
                                                        >
                                                            {item.name}
                                                            <Check
                                                                className={cn('ml-auto', fee.typeId === item.id ? 'opacity-100' : 'opacity-0')}
                                                            />
                                                        </CommandItem>
                                                    ))}
                                                </CommandGroup>
                                            </CommandList>
                                        </Command>
                                    </PopoverContent>
                                </Popover>

                            </div>
                            <div className="flex flex-col gap-1">
                                <Label htmlFor={`fee_name_${index}`}>{t('properties.step5', 'fee_name')}</Label>
                                <Input
                                    type="text"
                                    id={`fee_name_${index}`}
                                    value={fee.name}
                                    onChange={(e) => handleAdditionalFeeChange(index, 'name', e.target.value)}
                                    placeholder={t('properties.step5', 'enter_fee_name')}
                                    required
                                />
                            </div>
                            <div>
                                <Label htmlFor={`fee_discriminator_${index}`}>{t('properties.step5', 'calculation_type')}</Label>
                                <Select
                                    name={`fee_discriminator_${index}`}
                                    value={fee.discriminatorId}
                                    onValueChange={(value) => handleAdditionalFeeChange(index, 'discriminatorId', parseInt(value))}
                                    required
                                >
                                    <SelectTrigger className="mt-1">
                                        <SelectValue placeholder={t('properties.step5', 'select_discriminator')} />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectGroup>
                                            {feeDiscriminators.map((discriminator) => (
                                                <SelectItem key={discriminator.id} value={discriminator.id}>
                                                    {discriminator.name}
                                                </SelectItem>
                                            ))}
                                        </SelectGroup>
                                    </SelectContent>
                                </Select>
                            </div>
                            {FEE_DISCRIMINATORS_WITH_APPLIED_TO.includes(String(fee.discriminatorId)) && (
                                <div className="mt-4 flex flex-col gap-2">
                                    <Label>{t('properties.step5', 'applied_to')}</Label>
                                    <div className="flex flex-col gap-2">
                                        <label className="flex items-center gap-2">
                                            <Checkbox
                                                checked={fee.rent || false}
                                                onCheckedChange={(value) => handleAdditionalFeeChange(index, 'rent', value)}
                                            />
                                            <span>{t('properties.step5', 'rent')}</span>
                                        </label>
                                        <label className="flex items-center gap-2">
                                            <Checkbox
                                                checked={fee.cleaning_fee || false}
                                                onCheckedChange={(value) => handleAdditionalFeeChange(index, 'cleaning_fee', value)}
                                            />
                                            <span>{t('properties.step5', 'cleaning_fee')}</span>
                                        </label>
                                    </div>
                                </div>
                            )}
                            <div className="flex flex-col gap-1">
                                <Label htmlFor={`fee_amount_${index}`}>{t('properties.step5', 'value_usd')}</Label>
                                <Input
                                    type="number"
                                    id={`fee_amount_${index}`}
                                    value={fee.amount}
                                    onChange={(e) => handleAdditionalFeeChange(index, 'amount', parseFloat(e.target.value))}
                                    placeholder={t('properties.step5', 'enter_fee_amount')}
                                    required
                                />
                            </div>
                            <div>
                                <Label>{t('properties.step5', 'collection_time')}</Label>
                                <Select
                                    name={`fee_collect_time_${index}`}
                                    value={String(fee.collectTime)}
                                    onValueChange={(value) => handleAdditionalFeeChange(index, 'collectTime', parseInt(value))}
                                    required
                                >
                                    <SelectTrigger className="mt-1">
                                        <SelectValue placeholder={t('properties.step5', 'select_collection_time')} />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectGroup>
                                            <SelectItem value="1">{t('properties.step5', 'at_booking')}</SelectItem>
                                            <SelectItem value="2">{t('properties.step5', 'at_arrival')}</SelectItem>
                                        </SelectGroup>
                                    </SelectContent>
                                </Select>
                            </div>
                            {!MANDATORY_FEE_TYPES.includes(String(fee.typeId)) && (
                                <div className="mt-4 flex flex-col gap-2">
                                    <Label>{t('properties.step5', 'optionality')}</Label>
                                    <div className="flex flex-col gap-2">
                                        <label className="flex items-center gap-2">
                                            <Checkbox
                                                checked={fee.optional || false}
                                                onCheckedChange={(value) => handleAdditionalFeeChange(index, 'optional', value)}
                                            />
                                            <span className="text-sm">{t('properties.step5', 'optional')}</span>
                                        </label>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                        <Trash2Icon className="h-5 w-5 cursor-pointer text-red-500" onClick={() => handleRemoveAdditionalFee(index)} />
                    </div>
                    <InputError message={fieldErrors['additional_fee_' + index]} />
                </div>
            ))}
        </>
    );
}
