import { type ColumnDef } from "@tanstack/react-table";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { FileText, Building2, Download } from "lucide-react";
import { FormDialog } from "@/components/dialogs/form-dialog";
import { VersionTable } from "@/components/tables/version-table";
import { RequestUpdateMenu } from "@/components/menu/request-update-menu";
import { DeleteMenu } from "@/components/menu/delete-menu";
import { Button } from "@/components/ui/button";
import type { AxiosProgressEvent } from "axios";
import { useMemo, useState } from "react";
import { SelectDialog } from "@/components/dialogs/select-dialog";
import { DeviceSearchDialog } from "@/components/bars/device-searchbar";
import { UploadVersionForm } from "@/components/forms/upload-file-form";
import type { Room } from "@/types/room";
import { mapRoomsToSelectItems } from "@/helpers/mapRoomToSelectItems";
import { getDeviceFromRoom } from "@/services/device-comm.service";

interface AppManagerTemplateProps<TData> {
  title: string;
  uploadFormTitle?: string;
  description: string;
  data: TData[];
  isLoading: boolean;
  columns: ColumnDef<TData, any>[];
  onUpload: (
    fd: FormData,
    config?: { onUploadProgress?: (e: AxiosProgressEvent) => void }
  ) => Promise<void>;
  onUpdate?: (targetNames: string[]) => Promise<void> | void;
  updateLoading?: boolean;
  onDownload?: (targetNames: string[]) => Promise<void> | void;
  downloadLoading?: boolean;
  onDelete?: () => Promise<void> | void;
  onDeleteFromServer?: () => Promise<void> | void;
  onDeleteFromRequired?: () => Promise<void> | void;
  deleteLoading?: boolean;
  onAddToRequired?: () => Promise<void> | void;
  addToRequiredLoading?: boolean;
  onTableInit?: (table: any) => void;
  rooms?: Room[];
  devices?: string[];
  // Pagination options
  enablePagination?: boolean;
  defaultPageSize?: number;
  pageSizeOptions?: number[];
}

export function AppManagerTemplate<TData>({
  title,
  uploadFormTitle,
  description,
  data,
  isLoading,
  columns,
  onUpload,
  onUpdate,
  updateLoading,
  onDownload,
  downloadLoading,
  onDelete,
  onDeleteFromServer,
  onDeleteFromRequired,
  deleteLoading,
  onAddToRequired,
  addToRequiredLoading,
  onTableInit,
  rooms = [],
  devices = [],
  enablePagination = false,
  defaultPageSize = 10,
  pageSizeOptions = [5, 10, 15, 20],
}: AppManagerTemplateProps<TData>) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState<"room" | "device" | "download-room" | "download-device" | null>(null);

  const sortedData = useMemo(() => {
    const firstItem = data?.[0] as { fileName?: string } | undefined;
    if (!firstItem || typeof firstItem.fileName !== "string") {
      return data;
    }

    return [...data].sort((a, b) => {
      const aName = (a as { fileName?: string }).fileName ?? "";
      const bName = (b as { fileName?: string }).fileName ?? "";
      return aName.localeCompare(bName, "vi", {
        numeric: true,
        sensitivity: "base",
      });
    });
  }, [data]);

  const openRoomDialog = () => {
    if (rooms.length > 0 && onUpdate) {
      setDialogType("room");
      setDialogOpen(true);
    }
  };

  const openDeviceDialog = () => {
    if (onUpdate) {
      setDialogType("device");
      setDialogOpen(true);
    }
  };

  const openDownloadRoomDialog = () => {
    if (rooms.length > 0 && onDownload) {
      setDialogType("download-room");
      setDialogOpen(true);
    }
  };

  const openDownloadDeviceDialog = () => {
    if (onDownload) {
      setDialogType("download-device");
      setDialogOpen(true);
    }
  };

  const handleUpdateAll = async () => {
    if (!onUpdate) return;
    try {
      const roomIds = rooms.map((room) =>
        typeof room === "string" ? room : room.name
      );
      const allTargets = [...roomIds, ...devices];
      await onUpdate(allTargets);
    } catch (e) {
      console.error("Update error:", e);
    }
  };

  return (
    <div className="w-full px-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">{title}</h1>
          <p className="text-muted-foreground mt-2">{description}</p>
        </div>
        <FormDialog
          triggerLabel={uploadFormTitle || "Tải phiên bản mới"}
          title={uploadFormTitle || "Cập nhật phiên bản"}
        >
          {(closeDialog) => (
            <UploadVersionForm onSubmit={onUpload} closeDialog={closeDialog} />
          )}
        </FormDialog>
      </div>

      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5" /> Lịch sử phiên bản
          </CardTitle>
          <CardDescription>Tất cả các phiên bản đã tải lên</CardDescription>
        </CardHeader>

        <CardContent>
          <VersionTable
            data={sortedData}
            isLoading={isLoading}
            columns={columns}
            onTableInit={onTableInit}
            enablePagination={enablePagination}
            defaultPageSize={defaultPageSize}
            pageSizeOptions={pageSizeOptions}
          />
        </CardContent>

        {(onUpdate || onDelete || onAddToRequired) && (
          <CardFooter className="flex items-center justify-between gap-4">
            <div className="flex gap-2">
              <RequestUpdateMenu
                onUpdateDevice={openDeviceDialog}
                onUpdateRoom={openRoomDialog}
                onUpdateAll={handleUpdateAll}
                loading={updateLoading}
                label="Cài đặt"
                deviceLabel="Cài đặt thiết bị cụ thể"
                roomLabel="Cài đặt theo phòng"
                allLabel="Cài đặt tất cả thiết bị"
              />
              {onDownload && (
                <RequestUpdateMenu
                  onUpdateDevice={openDownloadDeviceDialog}
                  onUpdateRoom={openDownloadRoomDialog}
                  onUpdateAll={() => {
                    if (!onDownload) return;
                    const roomIds = rooms.map((room) =>
                      typeof room === "string" ? room : room.name
                    );
                    const allTargets = [...roomIds, ...devices];
                    onDownload(allTargets);
                  }}
                  loading={downloadLoading}
                  label="Tải xuống"
                  deviceLabel="Tải xuống thiết bị cụ thể"
                  roomLabel="Tải xuống theo phòng"
                  allLabel="Tải xuống tất cả thiết bị"
                  icon={<Download className="h-4 w-4" />}
                />
              )}
              {onAddToRequired && (
                <Button
                  onClick={onAddToRequired}
                  disabled={addToRequiredLoading}
                  className="gap-2"
                >
                  {addToRequiredLoading ? "Đang thêm..." : "Thêm vào danh sách"}
                </Button>
              )}
            </div>
            {onDeleteFromServer && onDeleteFromRequired && (
              <DeleteMenu
                onDeleteFromServer={onDeleteFromServer}
                onDeleteFromRequired={onDeleteFromRequired}
                loading={deleteLoading}
              />
            )}
          </CardFooter>
        )}
      </Card>

      {/* Dialog chọn phòng */}
      {dialogType === "room" && (
        <SelectDialog
          open={dialogOpen}
          onClose={() => {
            setDialogOpen(false);
            setDialogType(null);
            setTimeout(() => window.location.reload(), 500);
          }}
          title="Chọn phòng"
          description="Chọn các phòng cần cập nhật"
          icon={<Building2 className="w-6 h-6 text-primary" />}
          items={mapRoomsToSelectItems(rooms)}
          onConfirm={async (selectedItems) => {
            if (!onUpdate) return;
            try {
              await onUpdate(selectedItems);
            } catch (e) {
              console.error("Update error:", e);
            } finally {
              setDialogOpen(false);
              setDialogType(null);
              setTimeout(() => window.location.reload(), 500);
            }
          }}
        />
      )}

      {/* Dialog tìm thiết bị */}
      {dialogType === "device" && (
        <DeviceSearchDialog
          open={dialogOpen && dialogType === "device"}
          onClose={() => {
            setDialogOpen(false);
            setDialogType(null);
            setTimeout(() => window.location.reload(), 500);
          }}
          rooms={rooms}
          fetchDevices={getDeviceFromRoom}
          onSelect={async (deviceIds) => {
            if (!onUpdate) {
              setDialogOpen(false);
              setDialogType(null);
              return;
            }
            try {
              await onUpdate(deviceIds);
            } catch (e) {
              console.error("Update error:", e);
            } finally {
              setDialogOpen(false);
              setDialogType(null);
              setTimeout(() => window.location.reload(), 500);
            }
          }}
        />
      )}

      {/* Dialog tải file - chọn phòng */}
      {dialogType === "download-room" && (
        <SelectDialog
          open={dialogOpen}
          onClose={() => {
            setDialogOpen(false);
            setDialogType(null);
            setTimeout(() => window.location.reload(), 500);
          }}
          title="Chọn phòng"
          description="Chọn các phòng để tải file xuống"
          icon={<Building2 className="w-6 h-6 text-primary" />}
          items={mapRoomsToSelectItems(rooms)}
          onConfirm={async (selectedItems) => {
            if (!onDownload) return;
            try {
              await onDownload(selectedItems);
            } catch (e) {
              console.error("Download error:", e);
            } finally {
              setDialogOpen(false);
              setDialogType(null);
              setTimeout(() => window.location.reload(), 500);
            }
          }}
        />
      )}

      {/* Dialog tải file - tìm thiết bị */}
      {dialogType === "download-device" && (
        <DeviceSearchDialog
          open={dialogOpen && dialogType === "download-device"}
          onClose={() => {
            setDialogOpen(false);
            setDialogType(null);
            setTimeout(() => window.location.reload(), 500);
          }}
          rooms={rooms}
          fetchDevices={getDeviceFromRoom}
          onSelect={async (deviceIds) => {
            if (!onDownload) {
              setDialogOpen(false);
              setDialogType(null);
              return;
            }
            try {
              await onDownload(deviceIds);
            } catch (e) {
              console.error("Download error:", e);
            } finally {
              setDialogOpen(false);
              setDialogType(null);
              setTimeout(() => window.location.reload(), 500);
            }
          }}
        />
      )}
    </div>
  );
}
