import { type ColumnDef } from "@tanstack/react-table";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { FileText, Building2 } 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 type { AxiosProgressEvent } from "axios";
import { 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 { fetchDevicesFromRoom } from "@/services/device.service";

interface AppManagerTemplateProps<TData> {
  title: 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;
  onTableInit?: (table: any) => void;
  rooms?: Room[];
  devices?: string[];
}

export function AppManagerTemplate<TData>({
  title,
  description,
  data,
  isLoading,
  columns,
  onUpload,
  onUpdate,
  updateLoading,
  onDownload,
  downloadLoading,
  onTableInit,
  rooms = [],
  devices = [],
}: AppManagerTemplateProps<TData>) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState<"room" | "device" | "download-room" | "download-device" | null>(null);

  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="Tải lên phiên bản mới"
          title="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={data}
            isLoading={isLoading}
            columns={columns}
            onTableInit={onTableInit}
          />
        </CardContent>

        {onUpdate && (
          <CardFooter className="gap-2">
            <RequestUpdateMenu
              onUpdateDevice={openDeviceDialog}
              onUpdateRoom={openRoomDialog}
              onUpdateAll={handleUpdateAll}
              loading={updateLoading}
            />
            {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}
              />
            )}
          </CardFooter>
        )}
      </Card>

      {/* Dialog chọn phòng */}
      {dialogType === "room" && (
        <SelectDialog
          open={dialogOpen}
          onClose={() => {
            setDialogOpen(false);
            setDialogType(null);
          }}
          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);
          }}
          rooms={rooms}
          fetchDevices={fetchDevicesFromRoom}
          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);
          }}
          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);
          }}
          rooms={rooms}
          fetchDevices={fetchDevicesFromRoom}
          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>
  );
}
