// resources/assets/ts/ContactsPage/components/ContactsSearchView.tsx
import React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { blue, green, grey } from "@mui/material/colors";
import SearchBar from './SearchBar';
import DropdownFilter from './DropdownFilter';
import ContactsDataGrid from '../ContactsDataGrid';
import { handleCheckboxChange, isOnlyAlleSelected } from '../../utils/filterHandlers';
import { Option, Contact } from '../../types';
import Breadcrumbs from '@mui/material/Breadcrumbs';
import Link from '@mui/material/Link';
import SearchIcon from '@mui/icons-material/Search';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface ContactsSearchViewProps {
    // Search state
    searchTerm: string;
    onSearchChange: (value: string) => void;

    // Filter states
    statusFilter: Option[];
    brancheFilter: Option[];
    userFilter: Option[];
    verantwortlicherFilter: Option[];
    prioritaetFilter: Option[];

    // Filter setters
    setStatusFilter: React.Dispatch<React.SetStateAction<Option[]>>;
    setBrancheFilter: React.Dispatch<React.SetStateAction<Option[]>>;
    setUserFilter: React.Dispatch<React.SetStateAction<Option[]>>;
    setVerantwortlicherFilter: React.Dispatch<React.SetStateAction<Option[]>>;
    setPrioritaetFilter: React.Dispatch<React.SetStateAction<Option[]>>;

    // Data
    contacts: Contact[];
    loading: boolean;
    filtersLoading: boolean;

    // Datagrid Pagination props
    page: number;
    rowsPerPage: number;
    totalContacts: number;
    onPageChange: (newPage: number) => void;
    onRowsPerPageChange: (newRowsPerPage: number) => void;

    // Actions
    onResetFilters: () => void;
    onRemoveFilter: (type: 'status' | 'branche' | 'user' | 'verantwortlicher' | 'prioritaet', value?: string | number) => void;
}

const ContactsSearchView: React.FC<ContactsSearchViewProps> = ({
    searchTerm,
    onSearchChange,
    statusFilter,
    brancheFilter,
    userFilter,
    verantwortlicherFilter,
    prioritaetFilter,
    setStatusFilter,
    setBrancheFilter,
    setUserFilter,
    setVerantwortlicherFilter,
    setPrioritaetFilter,
    contacts,
    loading,
    filtersLoading,
    onResetFilters,
    onRemoveFilter,
    // Pagination props
    page,
    rowsPerPage,
    totalContacts,
    onPageChange,
    onRowsPerPageChange,
}) => {
    const { i18n } = useLingui();
    return (
        <>
            {/* Search input */}
            {/* <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
        <SearchBar value={searchTerm} onChange={onSearchChange} />
      </Box> */}

            {/* Show loading state while filters are being fetched */}
            {filtersLoading ? (
                <div className="text-center mb-3">
                    <div className="spinner-border text-primary" role="status">
                        <span className="sr-only"><Trans>Loading filters...</Trans></span>
                    </div>
                </div>
            ) : (
                <>

                         {/* Combined Search + Filters Row */}
                   <Box sx={{ p: { xs: 2, md: 3 } }} width="100%">
                        <Stack direction="row" spacing={2} flexWrap="wrap" alignItems="center" justifyContent="center">

                            {/* SEARCH BAR */}
                            <Box flex={1} minWidth={250}>
                                <SearchBar value={searchTerm} onChange={onSearchChange} />
                            </Box>

                            {/* FILTERS */}
                            <DropdownFilter
                                title={i18n._(msg`Categories`)}
                                options={statusFilter}
                                onChange={(updated) => {
                                    const changed = updated.find((opt, i) => opt.checked !== statusFilter[i]?.checked);
                                    if (changed) handleCheckboxChange(updated, setStatusFilter, changed.value as number | 'all', changed.checked);
                                }}
                                color={blue[500]}
                            />

                            <DropdownFilter
                                title={i18n._(msg`Industry`)}
                                options={brancheFilter}
                                onChange={(updated) => {
                                    const changed = updated.find((opt, i) => opt.checked !== brancheFilter[i]?.checked);
                                    if (changed) handleCheckboxChange(updated, setBrancheFilter, changed.value as number | 'all', changed.checked);
                                }}
                                color={green[500]}
                            />

                            <DropdownFilter
                                title={i18n._(msg`Creator`)}
                                options={userFilter}
                                onChange={(updated) => {
                                    const changed = updated.find((opt, i) => opt.checked !== userFilter[i]?.checked);
                                    if (changed) handleCheckboxChange(updated, setUserFilter, changed.value as string | 'all', changed.checked);
                                }}
                                color={grey[700]}
                            />

                            <DropdownFilter
                                title={i18n._(msg`Responsible`)}
                                options={verantwortlicherFilter}
                                onChange={(updated) => {
                                    const changed = updated.find((opt, i) => opt.checked !== verantwortlicherFilter[i]?.checked);
                                    if (changed) handleCheckboxChange(updated, setVerantwortlicherFilter, changed.value as string | 'all', changed.checked);
                                }}
                                color={blue[700]}
                            />

                            <DropdownFilter
                                title={i18n._(msg`Priority`)}
                                options={prioritaetFilter}
                                onChange={(updated) => {
                                    const changed = updated.find((opt, i) => opt.checked !== prioritaetFilter[i]?.checked);
                                    if (changed) handleCheckboxChange(updated, setPrioritaetFilter, changed.value as number | 'all', changed.checked);
                                }}
                                color={green[700]}
                            />

                            <Button variant="outlined" color="error" onClick={onResetFilters} sx={{ textTransform: 'none' }} >
                                <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                    <Trans>Reset</Trans>
                                </Typography>
                            </Button>

                        </Stack>
                    </Box>


                    {/* Active Filter Chips */}
                    {!loading && (
                        (!isOnlyAlleSelected(statusFilter) ||
                            !isOnlyAlleSelected(brancheFilter) ||
                            !isOnlyAlleSelected(userFilter) ||
                            !isOnlyAlleSelected(verantwortlicherFilter) ||
                            !isOnlyAlleSelected(prioritaetFilter)) && (
                            <Box mb={3} px={3} display="flex" flexDirection="column" alignItems="center">
                                <Typography fontWeight={600}><Trans>Active filters:</Trans></Typography>
                                <Stack mt={1} direction="row" spacing={1} flexWrap="wrap" justifyContent="center">
                                    {!isOnlyAlleSelected(statusFilter) &&
                                        statusFilter
                                            .filter((opt) => opt.checked && opt.value !== 'all')
                                            .map((opt) => (
                                                <Chip
                                                    key={opt.label}
                                                    label={opt.label}
                                                    variant="outlined"
                                                    sx={{ backgroundColor: blue[500], color: '#fff' }}
                                                    onDelete={() => onRemoveFilter('status', opt.value)}
                                                />
                                            ))}

                                    {!isOnlyAlleSelected(brancheFilter) &&
                                        brancheFilter
                                            .filter((opt) => opt.checked && opt.value !== 'all')
                                            .map((opt) => (
                                                <Chip
                                                    key={opt.label}
                                                    label={opt.label}
                                                    variant="outlined"
                                                    sx={{ backgroundColor: green[500], color: '#fff' }}
                                                    onDelete={() => onRemoveFilter('branche', opt.value)}
                                                />
                                            ))}

                                    {!isOnlyAlleSelected(userFilter) &&
                                        userFilter
                                            .filter((opt) => opt.checked && opt.value !== 'all')
                                            .map((opt) => (
                                                <Chip
                                                    key={opt.label}
                                                    label={opt.label}
                                                    variant="outlined"
                                                    sx={{ backgroundColor: grey[500], color: '#fff' }}
                                                    onDelete={() => onRemoveFilter('user', opt.value)}
                                                />
                                            ))}

                                    {!isOnlyAlleSelected(verantwortlicherFilter) &&
                                        verantwortlicherFilter
                                            .filter(opt => opt.checked && opt.value !== 'all')
                                            .map(opt => (
                                                <Chip
                                                    key={opt.label}
                                                    label={opt.label}
                                                    variant="outlined"
                                                    color="secondary"
                                                    onDelete={() => onRemoveFilter('verantwortlicher', opt.value)}
                                                />
                                            ))
                                    }

                                    {!isOnlyAlleSelected(prioritaetFilter) &&
                                        prioritaetFilter
                                            .filter(opt => opt.checked && opt.value !== 'all')
                                            .map(opt => (
                                                <Chip
                                                    key={opt.label}
                                                    label={opt.label}
                                                    variant="outlined"
                                                    color="success"
                                                    onDelete={() => onRemoveFilter('prioritaet', opt.value)}
                                                />
                                            ))
                                    }
                                </Stack>
                            </Box>
                        )
                    )}

                    <ContactsDataGrid
                        contacts={contacts}
                        loading={loading}
                        searchTerm={searchTerm}
                        page={page}
                        rowsPerPage={rowsPerPage}
                        totalContacts={totalContacts}
                        onPageChange={onPageChange}
                        onRowsPerPageChange={onRowsPerPageChange}
                    />
                </>
            )}
        </>
    );
};

export default ContactsSearchView;