'use client';

import { useState, useCallback, useEffect } from 'react';
import { useOrderFilters } from '../hooks/useOrderFilters';
import { useOrders } from '../hooks/useOrders';
import {
  Box,
  TextField,
  MenuItem,
  Button,
  Grid,
  Autocomplete,
  Paper,
  Tooltip,
  CircularProgress,
  Badge,
  Drawer,
  IconButton,
  Typography,
  Divider,
  Stack,
  type AutocompleteRenderInputParams,
} from '@mui/material';
import { useStores } from '../store/useStores';
import { useCustomers } from '../hooks/useCustomers';
import { useSellers } from '../hooks/useSellers';
import { usePartners } from '../hooks/usePartners';
import { useProducts } from '../hooks/useProducts';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import {
  Search as SearchIcon,
  RestartAlt as ResetIcon,
  Tune as TuneIcon,
  Close as CloseIcon,
} from '@mui/icons-material';
import moment from 'moment';
import 'moment/locale/pt-br';

moment.locale('pt-br');

interface LocalFilters {
  status: string | null;
  orderId: number | null;
  customerId: number | null;
  customerName: string | null;
  partnerId: string | null;
  partnerName: string | null;
  productId: number | null;
  productName: string | null;
  createDateIni: string | null;
  createDateEnd: string | null;
  store: string[] | null;
  stockId: string[] | null;
  sellerId: string | null;
  sellerName: string | null;
}

const getInitialLocalFilters = (
  urlFilters: Partial<LocalFilters>
): LocalFilters => ({
  status: urlFilters.status ?? null,
  orderId: urlFilters.orderId ?? null,
  customerId: urlFilters.customerId ?? null,
  customerName: urlFilters.customerName ?? null,
  partnerId: urlFilters.partnerId ?? null,
  partnerName: urlFilters.partnerName ?? null,
  productId: urlFilters.productId ?? null,
  productName: urlFilters.productName ?? null,
  createDateIni: urlFilters.createDateIni ?? null,
  createDateEnd: urlFilters.createDateEnd ?? null,
  store: urlFilters.store ?? null,
  stockId: urlFilters.stockId ?? null,
  sellerId: urlFilters.sellerId ?? null,
  sellerName: urlFilters.sellerName ?? null,
});

export const SearchBar = () => {
  const [urlFilters, setUrlFilters] = useOrderFilters();

  const [localFilters, setLocalFilters] = useState<LocalFilters>(() =>
    getInitialLocalFilters(urlFilters)
  );

  const stores = useStores();
  const sellers = useSellers();
  const [customerSearchTerm, setCustomerSearchTerm] = useState('');
  const customers = useCustomers(customerSearchTerm);
  const [partnerSearchTerm, setPartnerSearchTerm] = useState('');
  const partners = usePartners(partnerSearchTerm);
  const [productSearchTerm, setProductSearchTerm] = useState('');
  const products = useProducts(productSearchTerm);
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
  const { isFetching } = useOrders();
  const [touchedFields, setTouchedFields] = useState<{
    createDateIni?: boolean;
    createDateEnd?: boolean;
  }>({});

  useEffect(() => {
    setLocalFilters(getInitialLocalFilters(urlFilters));
  }, [urlFilters]);

  const updateLocalFilter = useCallback(
    <K extends keyof LocalFilters>(key: K, value: LocalFilters[K]) => {
      setLocalFilters((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  const handleReset = useCallback(() => {
    setTouchedFields({});
    setCustomerSearchTerm('');
    setPartnerSearchTerm('');
    setProductSearchTerm('');

    const resetState = {
      status: null,
      sellerName: null,
      sellerId: null,
      codfilial: null,
      codusur2: null,
      store: null,
      orderId: null,
      stockId: null,
      hasPreBox: false,
      includeCheckout: false,
      createDateIni: null,
      createDateEnd: null,
      searchTriggered: false,
      customerId: null,
      customerName: null,
      partnerId: null,
      partnerName: null,
      productId: null,
      productName: null,
    };

    setLocalFilters(getInitialLocalFilters(resetState));
    setUrlFilters(resetState);
  }, [setUrlFilters]);

  const validateDates = useCallback(() => {
    if (!localFilters.createDateIni || !localFilters.createDateEnd) {
      return null;
    }
    const dateIni = moment(localFilters.createDateIni, 'YYYY-MM-DD');
    const dateEnd = moment(localFilters.createDateEnd, 'YYYY-MM-DD');
    if (dateEnd.isBefore(dateIni)) {
      return 'Data final não pode ser anterior à data inicial';
    }
    return null;
  }, [localFilters.createDateIni, localFilters.createDateEnd]);

  const handleFilter = useCallback(() => {
    if (!localFilters.createDateIni) {
      setTouchedFields((prev) => ({ ...prev, createDateIni: true }));
      return;
    }

    const dateError = validateDates();
    if (dateError) {
      setTouchedFields((prev) => ({ ...prev, createDateEnd: true }));
      return;
    }

    setUrlFilters({
      ...localFilters,
      searchTriggered: true,
    });
  }, [localFilters, setUrlFilters, validateDates]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        const isValid = !!localFilters.createDateIni;
        const dateErr = validateDates();
        if (isValid && !dateErr) {
          handleFilter();
        }
      }
    },
    [localFilters.createDateIni, validateDates, handleFilter]
  );

  const isDateValid = !!localFilters.createDateIni;
  const dateError = validateDates();
  const showDateIniError =
    touchedFields.createDateIni && !localFilters.createDateIni;
  const showDateEndError = touchedFields.createDateEnd && dateError;

  // Contador de filtros ativos no Drawer
  const activeDrawerFiltersCount = [
    localFilters.status,
    localFilters.customerId,
    localFilters.store?.length,
    localFilters.stockId?.length,
    localFilters.sellerId,
    localFilters.partnerId,
    localFilters.productId,
  ].filter(Boolean).length;

  const toggleDrawer = (open: boolean) => (event: React.KeyboardEvent | React.MouseEvent) => {
    if (
      event.type === 'keydown' &&
      ((event as React.KeyboardEvent).key === 'Tab' ||
        (event as React.KeyboardEvent).key === 'Shift')
    ) {
      return;
    }
    setShowAdvancedFilters(open);
  };

  return (
    <Paper
      sx={{
        p: { xs: 2, md: 2 },
        mb: 2,
        bgcolor: 'background.paper',
        borderRadius: 2,
        boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
      }}
      elevation={0}
      onKeyDown={handleKeyDown}
    >
      <Grid container spacing={2} alignItems="center">
        {/* Nº do Pedido */}
        <Grid size={{ xs: 12, sm: 6, md: 2 }}>
          <TextField
            fullWidth
            label="Nº do Pedido"
            variant="outlined"
            size="small"
            type="number"
            value={localFilters.orderId ?? ''}
            onChange={(e) => {
              const value = e.target.value ? Number(e.target.value) : null;
              updateLocalFilter('orderId', value);
            }}
            slotProps={{ htmlInput: { min: 0 } }}
            placeholder="Ex: 12345"
          />
        </Grid>

        {/* Datas */}
        <Grid size={{ xs: 12, sm: 12, md: 5 }}>
          <LocalizationProvider dateAdapter={AdapterMoment} adapterLocale="pt-br">
            <Box display="flex" gap={1.5}>
              <DatePicker
                label="Data Inicial"
                value={localFilters.createDateIni ? moment(localFilters.createDateIni, 'YYYY-MM-DD') : null}
                onChange={(date) => {
                  setTouchedFields(prev => ({ ...prev, createDateIni: true }));
                  updateLocalFilter('createDateIni', date ? date.format('YYYY-MM-DD') : null);
                }}
                format="DD/MM/YYYY"
                slotProps={{
                  textField: {
                    size: 'small',
                    fullWidth: true,
                    required: true,
                    error: showDateIniError,
                    helperText: showDateIniError ? 'Obrigatório' : '',
                  }
                }}
              />
              <DatePicker
                label="Data Final"
                value={localFilters.createDateEnd ? moment(localFilters.createDateEnd, 'YYYY-MM-DD') : null}
                onChange={(date) => {
                  setTouchedFields(prev => ({ ...prev, createDateEnd: true }));
                  updateLocalFilter('createDateEnd', date ? date.format('YYYY-MM-DD') : null);
                }}
                format="DD/MM/YYYY"
                slotProps={{
                  textField: {
                    size: 'small',
                    fullWidth: true,
                    error: !!showDateEndError,
                    helperText: showDateEndError || '',
                  }
                }}
              />
            </Box>
          </LocalizationProvider>
        </Grid>

        {/* Ações */}
        <Grid size={{ xs: 12, md: 5 }} sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
          <Button
            variant="outlined"
            color="inherit"
            size="small"
            onClick={handleReset}
            startIcon={<ResetIcon />}
            sx={{ textTransform: 'none', minWidth: 90 }}
          >
            Limpar
          </Button>

          <Badge badgeContent={activeDrawerFiltersCount} color="primary">
            <Button
              variant="outlined"
              color="primary"
              size="small"
              onClick={toggleDrawer(true)}
              startIcon={<TuneIcon />}
              sx={{ textTransform: 'none', minWidth: 100 }}
            >
              Filtros
            </Button>
          </Badge>

          <Button
            variant="contained"
            color="primary"
            size="small"
            onClick={handleFilter}
            disabled={!isDateValid || !!dateError || isFetching}
            startIcon={isFetching ? <CircularProgress size={16} color="inherit" /> : <SearchIcon />}
            sx={{ textTransform: 'none', minWidth: 100 }}
          >
            Buscar
          </Button>
        </Grid>
      </Grid>

      {/* Sidebar de Filtros */}
      <Drawer
        anchor="right"
        open={showAdvancedFilters}
        onClose={toggleDrawer(false)}
        PaperProps={{
          sx: { width: { xs: '100%', sm: 400 }, p: 0 }
        }}
      >
        <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
          {/* Header */}
          <Box sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid', borderColor: 'divider' }}>
            <Typography variant="h6" sx={{ fontWeight: 600 }}>Todos os Filtros</Typography>
            <IconButton onClick={toggleDrawer(false)} size="small">
              <CloseIcon />
            </IconButton>
          </Box>

          {/* Filtros Content */}
          <Box sx={{ p: 3, flex: 1, overflowY: 'auto' }}>
            <Stack spacing={3}>
              {/* Situação */}
              <TextField
                select
                fullWidth
                label="Situação"
                size="small"
                value={localFilters.status ?? ''}
                onChange={(e) => updateLocalFilter('status', e.target.value || null)}
              >
                <MenuItem value="">Todos</MenuItem>
                <MenuItem value="P">Pendente</MenuItem>
                <MenuItem value="F">Faturado</MenuItem>
                <MenuItem value="C">Cancelado</MenuItem>
              </TextField>

              {/* Cliente */}
              <Autocomplete
                size="small"
                options={customers.options}
                getOptionLabel={(option) => option.label}
                isOptionEqualToValue={(option, value) => option.id === value.id}
                value={customers.options.find(opt => localFilters.customerId === opt.customer?.id) || null}
                onChange={(_, newValue) => {
                  updateLocalFilter('customerId', newValue?.customer?.id || null);
                  updateLocalFilter('customerName', newValue?.customer?.name || null);
                }}
                onInputChange={(_, val) => setCustomerSearchTerm(val)}
                loading={customers.isLoading}
                renderInput={(params) => <TextField {...params} label="Cliente" placeholder="Buscar cliente..." />}
                noOptionsText={customerSearchTerm.length < 2 ? 'Digite 2+ caracteres' : 'Nenhum cliente'}
                filterOptions={(x) => x}
              />

              {/* Filiais */}
              <Autocomplete
                multiple
                size="small"
                options={stores.options}
                getOptionLabel={(option) => option.label}
                isOptionEqualToValue={(option, value) => option.id === value.id}
                value={stores.options.filter((opt) => localFilters.store?.includes(opt.value))}
                onChange={(_, newValue) => updateLocalFilter('store', newValue.map((opt) => opt.value))}
                loading={stores.isLoading}
                renderInput={(params) => <TextField {...params} label="Filiais" placeholder="Selecione filiais" />}
              />

              {/* Filial de Estoque */}
              <Autocomplete
                multiple
                size="small"
                options={stores.options}
                getOptionLabel={(option) => option.label}
                isOptionEqualToValue={(option, value) => option.id === value.id}
                value={stores.options.filter((opt) => localFilters.stockId?.includes(opt.value))}
                onChange={(_, newValue) => updateLocalFilter('stockId', newValue.map((opt) => opt.value))}
                loading={stores.isLoading}
                renderInput={(params) => <TextField {...params} label="Filial de Estoque" placeholder="Selecione filial" />}
              />

              {/* Vendedor */}
              <Autocomplete
                size="small"
                options={sellers.options}
                getOptionLabel={(option) => option.label}
                value={sellers.options.find(opt => localFilters.sellerId === opt.seller.id.toString()) || null}
                onChange={(_, newValue) => {
                  updateLocalFilter('sellerId', newValue?.seller.id.toString() || null);
                  updateLocalFilter('sellerName', newValue?.seller.name || null);
                }}
                loading={sellers.isLoading}
                renderInput={(params) => <TextField {...params} label="Vendedor" placeholder="Selecione vendedor" />}
              />

              {/* Parceiro */}
              <Autocomplete
                size="small"
                options={partners.options}
                getOptionLabel={(option) => option.label}
                value={partners.options.find(opt => localFilters.partnerId === opt.partner?.id?.toString()) || null}
                onChange={(_, newValue) => {
                  updateLocalFilter('partnerId', newValue?.partner?.id?.toString() || null);
                  updateLocalFilter('partnerName', newValue?.partner?.nome || null);
                }}
                onInputChange={(_, val) => setPartnerSearchTerm(val)}
                loading={partners.isLoading}
                renderInput={(params) => <TextField {...params} label="Parceiro" placeholder="Buscar parceiro..." />}
                noOptionsText={partnerSearchTerm.length < 2 ? 'Digite 2+ caracteres' : 'Nenhum parceiro'}
                filterOptions={(x) => x}
              />

              {/* Produto */}
              <Autocomplete
                size="small"
                options={products.options}
                getOptionLabel={(option) => option.label}
                value={products.options.find(opt => localFilters.productId === opt.product?.id) || null}
                onChange={(_, newValue) => {
                  updateLocalFilter('productId', newValue?.product?.id || null);
                  updateLocalFilter('productName', newValue?.product?.description || null);
                }}
                onInputChange={(_, val) => setProductSearchTerm(val)}
                loading={products.isLoading}
                renderInput={(params) => <TextField {...params} label="Produto" placeholder="Buscar produto..." />}
                noOptionsText={productSearchTerm.length < 2 ? 'Digite 2+ caracteres' : 'Nenhum produto'}
                filterOptions={(x) => x}
              />

            </Stack>
          </Box>

          {/* Footer */}
          <Box sx={{ p: 2, borderTop: '1px solid', borderColor: 'divider', display: 'flex', gap: 2 }}>
            <Button fullWidth variant="outlined" color="inherit" onClick={handleReset}>Limpar</Button>
            <Button fullWidth variant="contained" color="primary" onClick={() => { handleFilter(); setShowAdvancedFilters(false); }}>Aplicar</Button>
          </Box>
        </Box>
      </Drawer>
    </Paper>
  );
};
