"use client";

import SearchBox, { Criterion } from "../SearchBox";
import { useCallback, useMemo, useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import DeleteIcon from "@mui/icons-material/Delete";
import { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import useUploadContext from "../UploadProvider/useUploadContext";
import { downloadFile } from "@/app/utils/commonUtil";
import { UserResult } from "@/app/api/user";
import { deleteUser } from "@/app/api/user/actions";
import QrCodeIcon from "@mui/icons-material/QrCode";
import { exportUserQrCode, printUserQrCode, searchUsersByUsernameOrName } from "@/app/api/user/client";
import { 
  Checkbox, 
  Box, 
  Button, 
  TextField, 
  Stack, 
  Autocomplete, 
  Modal, 
  Card, 
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography
} from "@mui/material";
import DownloadIcon from "@mui/icons-material/Download";
import PrintIcon from "@mui/icons-material/Print";
import CloseIcon from "@mui/icons-material/Close";
import { PrinterCombo } from "@/app/api/settings/printer";

interface Props {
  users: UserResult[];
  printerCombo: PrinterCombo[];
}

type SearchQuery = Partial<Omit<UserResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const QrCodeHandleSearch: React.FC<Props> = ({ users, printerCombo }) => {
  const { t } = useTranslation("user");
  const [filteredUser, setFilteredUser] = useState(users);
  const router = useRouter();
  const { setIsUploading } = useUploadContext();
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  const [checkboxIds, setCheckboxIds] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  const [printQty, setPrintQty] = useState(1);
  const [isSearching, setIsSearching] = useState(false);

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  const [selectedUsersModalOpen, setSelectedUsersModalOpen] = useState(false);

  const filteredPrinters = useMemo(() => {
      return printerCombo.filter((printer) => {
          return printer.type === "A4";
      });
  }, [printerCombo]);

  const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | undefined>(
    filteredPrinters.length > 0 ? filteredPrinters[0] : undefined
  );

  useEffect(() => {
    if (!selectedPrinter || !filteredPrinters.find(p => p.id === selectedPrinter.id)) {
      setSelectedPrinter(filteredPrinters.length > 0 ? filteredPrinters[0] : undefined);
    }
  }, [filteredPrinters, selectedPrinter]);

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: "用戶/姓名",
        paramName: "username",
        type: "text",
      },
      {
        label: t("staffNo"),
        paramName: "staffNo",
        type: "text",
      },
    ],
    [t],
  );

  const onDeleteClick = useCallback((user: UserResult) => {
    deleteDialog(async () => {
      await deleteUser(user.id);
      successDialog(t("Delete Success"), t);
    }, t);
  }, [t]);

  const handleSelectUser = useCallback((userId: number, checked: boolean) => {
    if (checked) {
      setCheckboxIds(prev => [...prev, userId]);
    } else {
      setCheckboxIds(prev => prev.filter(id => id !== userId));
      setSelectAll(false);
    }
  }, []);

  const handleSelectAll = useCallback((checked: boolean) => {
    if (checked) {
      setCheckboxIds(filteredUser.map(user => user.id));
      setSelectAll(true);
    } else {
      setCheckboxIds([]);
      setSelectAll(false);
    }
  }, [filteredUser]);


  const showPdfPreview = useCallback(async (userIds: number[]) => {
      if (userIds.length === 0) {
        return;
      }
      try {
        setIsUploading(true);
        const response = await exportUserQrCode(userIds);
        
        const blob = new Blob([new Uint8Array(response.blobValue)], { type: "application/pdf" });
        const url = URL.createObjectURL(blob);
      
        setPreviewUrl(`${url}#toolbar=0`);
        setPreviewOpen(true);
      } catch (error) {
        console.error("Error exporting QR code:", error);
      } finally {
        setIsUploading(false);
      }
    }, [setIsUploading]);


  const handleClosePreview = useCallback(() => {
    setPreviewOpen(false);
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      setPreviewUrl(null);
    }
  }, [previewUrl]);

  const handleDownloadQrCode = useCallback(async (userIds: number[]) => {
    if (userIds.length === 0) {
      return;
    }
    try {
      setIsUploading(true);
      const response = await exportUserQrCode(userIds);
      downloadFile(response.blobValue, response.filename);
      setSelectedUsersModalOpen(false);
      successDialog("二維碼已下載", t);
    } catch (error) {
      console.error("Error exporting QR code:", error);
    } finally {
      setIsUploading(false);
    }
  }, [setIsUploading, t]);

  const handlePrint = useCallback(async () => {
    if (checkboxIds.length === 0 || !selectedPrinter) {
      return;
    }
    try {
      setIsUploading(true);
      await printUserQrCode({
        userIds: checkboxIds,
        printerId: selectedPrinter.id,
        printQty,
      });
      setSelectedUsersModalOpen(false);
      successDialog("二維碼已列印", t);
    } catch (error) {
      console.error("Error printing QR code:", error);
    } finally {
      setIsUploading(false);
    }
  }, [checkboxIds, printQty, selectedPrinter, setIsUploading, t]);

  const handleViewSelectedQrCodes = useCallback(() => {
    if (checkboxIds.length === 0) {
      return;
    }
    setSelectedUsersModalOpen(true);
  }, [checkboxIds]);

  const selectedUsers = useMemo(() => {
    return users.filter(user => checkboxIds.includes(user.id));
  }, [users, checkboxIds]);

  const handleCloseSelectedUsersModal = useCallback(() => {
    setSelectedUsersModalOpen(false);
  }, []);

  const columns = useMemo<Column<UserResult>[]>(
    () => [
      {
        name: "id",
        label: "", 
        sx: { width: "50px", minWidth: "50px" },
        renderCell: (params) => (
          <Checkbox
            checked={checkboxIds.includes(params.id)}
            onChange={(e) => handleSelectUser(params.id, e.target.checked)}
            onClick={(e) => e.stopPropagation()}
          />
        ),
      },
      { 
        name: "username", 
        label: t("User"),
        align: "left",
        headerAlign: "left",
        sx: { width: "150px", minWidth: "150px" },
      },
      {
        name: "name",
        label: t("name"),
        align: "left",
        headerAlign: "left",
        sx: { width: "150px", minWidth: "150px" },
      },
      {
        name: "staffNo",
        label: t("staffNo"),
        align: "left",
        headerAlign: "left",
        sx: { width: "150px", minWidth: "150px" },
      },
    ],
    [t, checkboxIds, handleSelectUser],
  );

  const onReset = useCallback(() => {
    setFilteredUser(users);
  }, [users]);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={async (query) => {
          setIsSearching(true);
          try {
            let results: UserResult[] = [];

            if (query.username && query.username.trim()) {
              // Search by username OR name from database
              results = await searchUsersByUsernameOrName(query.username);
            } else {
              // If no username search, start with all users
              results = users;
            }

            // Then filter by staffNo if provided (client-side filtering)
            if (query.staffNo && query.staffNo.trim()) {
              results = results.filter((user) =>
                user.staffNo?.toString().includes(query.staffNo?.toString() || "")
              );
            }

            setFilteredUser(results);
            setPagingController({ pageNum: 1, pageSize: 10 });
          } catch (error) {
            console.error("Error searching users:", error);
            // Fallback to client-side filtering on error
            setFilteredUser(
              users.filter((user) => {
                const userMatch = !query.username || 
                  user.username?.toLowerCase().includes(query.username?.toLowerCase() || "") ||
                  user.name?.toLowerCase().includes(query.username?.toLowerCase() || "");
                const staffNoMatch = !query.staffNo || 
                  user.staffNo?.toString().includes(query.staffNo?.toString() || "");
                return userMatch && staffNoMatch;
              })
            );
          } finally {
            setIsSearching(false);
          }
        }}
        onReset={onReset}
      />
      <SearchResults<UserResult>
        items={filteredUser}
        columns={columns}
        pagingController={pagingController}
        setPagingController={setPagingController}
        totalCount={filteredUser.length}
        isAutoPaging={true}
      />
      <Box sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
        <Button
          variant="outlined"
          onClick={() => handleSelectAll(!selectAll)}
          startIcon={<Checkbox checked={selectAll} />}
        >
          選擇全部用戶 ({checkboxIds.length} / {filteredUser.length})
        </Button>
        <Button 
          variant="contained" 
          onClick={handleViewSelectedQrCodes}
          disabled={checkboxIds.length === 0}
          color="primary"
        >
          查看已選擇用戶二維碼 ({checkboxIds.length})
        </Button>
      </Box>

      <Modal
        open={selectedUsersModalOpen}
        onClose={handleCloseSelectedUsersModal}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Card
          sx={{
            position: 'relative',
            width: '90%',
            maxWidth: '800px',
            maxHeight: '90vh',
            display: 'flex',
            flexDirection: 'column',
            outline: 'none',
          }}
        >
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              p: 2,
              borderBottom: 1,
              borderColor: 'divider',
            }}
          >
            <Typography variant="h6" component="h2">
              已選擇用戶 ({selectedUsers.length})
            </Typography>
            <IconButton onClick={handleCloseSelectedUsersModal}>
              <CloseIcon />
            </IconButton>
          </Box>

          <Box
            sx={{
              flex: 1,
              overflow: 'auto',
              p: 2,
            }}
          >
            <TableContainer component={Paper} variant="outlined">
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>
                      <strong>{t("name")}</strong>
                    </TableCell>
                    <TableCell>
                      <strong>{t("staffNo")}</strong>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {selectedUsers.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={2} align="center">
                        沒有選擇的用戶
                      </TableCell>
                    </TableRow>
                  ) : (
                    selectedUsers.map((user) => (
                      <TableRow key={user.id}>
                        <TableCell>{user.name || '-'}</TableCell>
                        <TableCell>{user.staffNo || '-'}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Box>

          <Box
            sx={{
              p: 2,
              borderTop: 1,
              borderColor: 'divider',
              bgcolor: 'background.paper',
            }}
          >
            <Stack direction="row" justifyContent="flex-end" alignItems="center" gap={2}>
              <Autocomplete<PrinterCombo>
                options={filteredPrinters}
                value={selectedPrinter ?? null}
                onChange={(event, value) => {
                  setSelectedPrinter(value ?? undefined);
                }}
                getOptionLabel={(option) => option.name || option.label || option.code || String(option.id)}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    variant="outlined"
                    label="列印機"
                    sx={{ width: 300 }}
                  />
                )}
              />
              <TextField
                variant="outlined"
                label="列印數量"
                type="number"
                value={printQty}
                onChange={(e) => {
                  const value = parseInt(e.target.value) || 1;
                  setPrintQty(Math.max(1, value));
                }}
                inputProps={{ min: 1 }}
                sx={{ width: 120 }}
              />
              <Button
                variant="contained"
                startIcon={<PrintIcon />}
                onClick={handlePrint}
                disabled={checkboxIds.length === 0 || filteredPrinters.length === 0 || !selectedPrinter}
                color="primary"
              >
                列印
              </Button>
              <Button
                variant="contained"
                startIcon={<DownloadIcon />}
                onClick={() => handleDownloadQrCode(checkboxIds)}
                disabled={checkboxIds.length === 0}
                color="primary"
              >
                下載二維碼
              </Button>
            </Stack>
          </Box>
        </Card>
      </Modal>

      <Modal
        open={previewOpen}
        onClose={handleClosePreview}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Card
          sx={{
            position: 'relative',
            width: '90%',
            maxWidth: '900px',
            maxHeight: '90vh',
            display: 'flex',
            flexDirection: 'column',
            outline: 'none',
          }}
        >
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'flex-end',
              alignItems: 'center',
              p: 2,
              borderBottom: 1,
              borderColor: 'divider',
            }}
          >
            <IconButton
              onClick={handleClosePreview}
            >
              <CloseIcon />
            </IconButton>
          </Box>

          <Box
            sx={{
              flex: 1,
              overflow: 'auto',
              p: 2,
            }}
          >
            {previewUrl && (
              <iframe
                src={previewUrl}
                width="100%"
                height="600px"
                style={{
                  border: 'none',
                }}
                title="PDF Preview"
              />
            )}
          </Box>
        </Card>
      </Modal>
    </>
  );
};

export default QrCodeHandleSearch;