"use client";
import {
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Grid,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults/SearchResults";
import { fetchConsoPickOrderClient } from "@/app/api/pickOrder/actions";
import { fetchNameList, NameList } from "@/app/api/user/actions";
import { isEmpty, upperFirst } from "lodash";
import { arrayToDateString } from "@/app/utils/formatUtil";

interface Props {
  filterArgs: Record<string, any>;
}

interface AssignmentData {
  id: string;
  consoCode: string;
  releasedDate: string | null;
  status: string;
  assignTo: number | null;
  assignedUserName?: string;
}

const AssignTo: React.FC<Props> = ({ filterArgs }) => {
  const { t } = useTranslation("pickOrder");
  
  // State
  const [assignmentData, setAssignmentData] = useState<AssignmentData[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 50,
  });
  const [totalCount, setTotalCount] = useState<number>();
  const [usernameList, setUsernameList] = useState<NameList[]>([]);
  const [selectedUser, setSelectedUser] = useState<NameList | null>(null);

  // Fetch assignment data
  const fetchAssignmentData = useCallback(async () => {
    setIsLoading(true);
    try {
      const params = {
        ...pagingController,
        ...filterArgs,
        // Add user filter if selected
        ...(selectedUser && { assignTo: selectedUser.id }),
      };
      
      console.log("Fetching with params:", params);
      
      const res = await fetchConsoPickOrderClient(params);
      if (res) {
        console.log("API response:", res);
        
        // Enhance data with user names and add id
        const enhancedData = res.records.map((record: any, index: number) => {
          const userName = record.assignTo 
            ? usernameList.find(user => user.id === record.assignTo)?.name 
            : null;
          
          return {
            ...record,
            id: record.consoCode || `temp-${index}`,
            assignedUserName: userName || 'Unassigned',
          };
        });
        
        setAssignmentData(enhancedData);
        setTotalCount(res.total);
      }
    } catch (error) {
      console.error("Error fetching assignment data:", error);
    } finally {
      setIsLoading(false);
    }
  }, [pagingController, filterArgs, selectedUser, usernameList]);

  // Load username list
  useEffect(() => {
    const loadUsernameList = async () => {
      try {
        const res = await fetchNameList();
        if (res) {
          console.log("Loaded username list:", res);
          setUsernameList(res);
        }
      } catch (error) {
        console.error("Error loading username list:", error);
      }
    };
    loadUsernameList();
  }, []);

  // Fetch data when dependencies change
  useEffect(() => {
    fetchAssignmentData();
  }, [fetchAssignmentData]);

  // Handle user selection
  const handleUserChange = useCallback((event: any, newValue: NameList | null) => {
    setSelectedUser(newValue);
    // Reset to first page when filtering
    setPagingController(prev => ({ ...prev, pageNum: 1 }));
  }, []);

  // Clear filter
  const handleClearFilter = useCallback(() => {
    setSelectedUser(null);
    setPagingController(prev => ({ ...prev, pageNum: 1 }));
  }, []);

  // Columns definition
  const columns = useMemo<Column<AssignmentData>[]>(
    () => [
      {
        name: "consoCode",
        label: t("Consolidated Code"),
      },
      {
        name: "assignedUserName",
        label: t("Assigned To"),
        renderCell: (params) => {
          if (!params.assignTo) {
            return (
              <Typography variant="body2" color="text.secondary">
                {t("Unassigned")}
              </Typography>
            );
          }
          return (
            <Typography variant="body2" color="primary">
              {params.assignedUserName}
            </Typography>
          );
        },
      },
      {
        name: "status",
        label: t("Status"),
        renderCell: (params) => {
          return upperFirst(params.status);
        },
      },
      {
        name: "releasedDate",
        label: t("Released Date"),
        renderCell: (params) => {
          if (!params.releasedDate) {
            return (
              <Typography variant="body2" color="text.secondary">
                {t("Not Released")}
              </Typography>
            );
          }
          return arrayToDateString(params.releasedDate);
        },
      },
    ],
    [t],
  );

  return (
    <Stack spacing={2}>
      {/* Filter Section */}
      <Grid container spacing={2}>
        <Grid item xs={4}>
          <Autocomplete
            options={usernameList}
            getOptionLabel={(option) => option.name}
            value={selectedUser}
            onChange={handleUserChange}
            renderInput={(params) => (
              <TextField
                {...params}
                label={t("Select User to Filter")}
                variant="outlined"
                fullWidth
              />
            )}
            renderOption={(props, option) => (
              <Box component="li" {...props}>
                <Typography variant="body2">
                  {option.name} (ID: {option.id})
                </Typography>
              </Box>
            )}
          />
        </Grid>
        <Grid item xs={2}>
          <Button
            variant="outlined"
            onClick={handleClearFilter}
            disabled={!selectedUser}
          >
            {t("Clear Filter")}
          </Button>
        </Grid>
      </Grid>

      {/* Data Table - Match PickExecution exactly */}
      <Grid container spacing={2} sx={{ height: '100%', flex: 1 }}>
        <Grid item xs={12} sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          {isLoading ? (
            <Box display="flex" justifyContent="center" alignItems="center" flex={1}>
              <CircularProgress size={40} />
            </Box>
          ) : (
            <SearchResults<AssignmentData>
              items={assignmentData}
              columns={columns}
              pagingController={pagingController}
              setPagingController={setPagingController}
              totalCount={totalCount}
            />
          )}
        </Grid>
      </Grid>
    </Stack>
  );
};

export default AssignTo;


