import { useState, useEffect } from 'react';
import FieldBase, { FieldProps } from './FieldBase';
import { Button } from "@/components/ui/button";
import RelationModal from './RelationModal';
import RelationEntriesTable from '@/components/ui/relation-entries-table';
import { ContentEntry, Field as CollectionField } from '@/types';
import { PlusIcon, TrashIcon } from 'lucide-react';
import axios from 'axios';

export default function RelationField({ field, value, onChange, processing, errors }: FieldProps) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [selectedEntries, setSelectedEntries] = useState<ContentEntry[]>([]);
    const [displayFields, setDisplayFields] = useState<CollectionField[]>([]);

    const handleSelectedItems = (
        items: ContentEntry | ContentEntry[] | number | number[],
        fields: CollectionField[]
    ) => {
        if (field.options?.relation?.type === 1) {
            const id = typeof items === 'object' ? (items as ContentEntry).id : items as number;
            onChange(field, id);
            if (typeof items === 'object') {
                setSelectedEntries([items as ContentEntry]);
            }
        } else {
            let ids: number[] = [];
            if (Array.isArray(items)) {
                ids = items.map((item: any) => (typeof item === 'object' ? item.id : item));
                // Replace table data with the received objects (filter out primitives)
                const objs = items.filter((i: any) => typeof i === 'object') as ContentEntry[];
                setSelectedEntries(objs);
            } else {
                ids = [typeof items === 'object' ? (items as ContentEntry).id : (items as number)];
                if (typeof items === 'object') {
                    setSelectedEntries([items as ContentEntry]);
                }
            }
            onChange(field, ids);
        }

        // Save fields for display table (exclude hidden fields)
        const filtered = fields.filter(f => !f.options?.hideInContentList && f.type !== 'password' && f.type !== 'json');
        setDisplayFields(filtered);
    }
    
    // Load existing entries (edit mode)
    useEffect(() => {
        if (!value || selectedEntries.length > 0) return;

        let ids: number[] = [];
        if (Array.isArray(value)) {
            ids = value as number[];
        } else if (typeof value === 'number') {
            ids = [value];
        }

        if (ids.length === 0) return;

        const collectionId = field.options?.relation?.collection;
        if (!collectionId) return;

        let findUrl: string;
        if (typeof route === 'function') {
            try {
                findUrl = route('projects.collections.content.find', {
                    project: field.project_id,
                    collection: collectionId,
                });
            } catch {
                findUrl = `/projects/${field.project_id}/collections/${collectionId}/content/find`;
            }
        } else {
            findUrl = `/projects/${field.project_id}/collections/${collectionId}/content/find`;
        }

        axios
            .get(findUrl, {
                params: { ids: ids.join(',') },
            })
            .then(res => {
                setSelectedEntries(res.data);

                // Need display fields; fetch relation collection definition
                let collUrl: string;
                if (typeof route === 'function') {
                    try {
                        collUrl = route('projects.collections.content.getRelationCollection', {
                            project: field.project_id,
                            collection: collectionId,
                        });
                    } catch {
                        collUrl = `/projects/${field.project_id}/collections/${collectionId}/content/relation-collection`;
                    }
                } else {
                    collUrl = `/projects/${field.project_id}/collections/${collectionId}/content/relation-collection`;
                }
                return axios.get(collUrl);
            })
            .then(res => {
                const relFields: CollectionField[] = res.data.fields || [];
                const filtered = relFields.filter(f => !f.options?.hideInContentList && f.type !== 'password' && f.type !== 'json');
                setDisplayFields(filtered);
            })
            .catch(() => {});

    }, [value]);

    return (
        <FieldBase field={field} value={value} onChange={onChange} processing={processing} errors={errors}>
            <div className="flex flex-col gap-2">
                <div className="flex gap-2">
                    <Button 
                        type="button" 
                        variant="outline"
                        disabled={processing}
                        onClick={() => setIsModalOpen(true)}
                    >
                        <PlusIcon className="w-4 h-4" />
                        {selectedEntries.length > 0 ? (field.options?.relation?.type === 1 ? 'Change Relation Entry' : 'Change Relation Entries') : (field.options?.relation?.type === 1 ? 'Select Relation Entry' : 'Select Relation Entries')}
                    </Button>

                    {selectedEntries.length > 0 && (
                        <Button 
                            type="button" 
                            variant="outline" 
                            disabled={processing} 
                            onClick={() => {
                                setSelectedEntries([]);
                                onChange(field, []);
                            }}>
                            <TrashIcon className="w-4 h-4" />
                            Clear Selected
                        </Button>
                    )}
                </div>
                {selectedEntries.length > 0 && (
                    <RelationEntriesTable
                        fields={displayFields}
                        entries={selectedEntries}
                        showStatus={false}
                        showCreated={false}
                    />
                )}
            </div>

            {isModalOpen && (
                <RelationModal
                    isOpen={isModalOpen}
                    onClose={() => setIsModalOpen(false)}
                    field={field}
                    value={selectedEntries}
                    onSelect={handleSelectedItems}
                />
            )}
        </FieldBase>
    );
}

/* Removed duplicate renderFieldValue – now handled by RelationEntriesTable */ 