import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Printer, FileText, Paperclip, AlertCircle } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { Checkbox } from "@/shared/common/ui/checkbox";
import { Label } from "@/shared/common/ui/label";
import { Separator } from "@/shared/common/ui/separator";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { toast } from "sonner";
import type {
  PrintOptions,
  AttachmentFile,
} from "@/record-management/utils/printService";
import {
  printRecordWithAttachments,
  validatePrintOptions,
} from "@/record-management/utils/printService";

interface PrintDialogProps {
  isOpen: boolean;
  onClose: () => void;
  pdfUrl: string;
  attachments: AttachmentFile[];
}

export const PrintDialog: React.FC<PrintDialogProps> = ({
  isOpen,
  onClose,
  pdfUrl,
  attachments,
}) => {
  const { t } = useTranslation();
  const [isLoading, setIsLoading] = useState(false);
  const [options, setOptions] = useState<PrintOptions>({
    includeRecord: true,
    includeAttachments: attachments.length > 0,
    attachmentIndices: attachments.map((_, idx) => idx),
  });

  // Log files when dialog opens
  React.useEffect(() => {
    if (isOpen) {
    }
  }, [isOpen, pdfUrl, attachments]);

  const handleRecordToggle = (checked: boolean) => {
    setOptions((prev) => ({
      ...prev,
      includeRecord: checked,
    }));
  };

  const handleAttachmentsToggle = (checked: boolean) => {
    setOptions((prev) => ({
      ...prev,
      includeAttachments: checked,
      attachmentIndices: checked ? attachments.map((_, idx) => idx) : [],
    }));
  };

  const handleAttachmentToggle = (index: number, checked: boolean) => {
    setOptions((prev) => {
      const indices = prev.attachmentIndices || [];
      if (checked) {
        return {
          ...prev,
          attachmentIndices: [...indices, index],
        };
      } else {
        return {
          ...prev,
          attachmentIndices: indices.filter((i) => i !== index),
        };
      }
    });
  };

  const handlePrint = async () => {
    if (!validatePrintOptions(options)) {
      toast.error(
        t("print.selectAtLeastOne") ||
          "Please select at least one item to print",
      );
      return;
    }

    try {
      setIsLoading(true);
      await printRecordWithAttachments(pdfUrl, attachments, options);
      toast.success(t("print.success") || "Print job sent successfully");
      // Wait for all print windows to open before closing
      setTimeout(() => {
        onClose();
      }, 3000);
    } catch (error) {
      console.error("Print error:", error);
      toast.error(t("print.error") || "Failed to print. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  const selectedCount =
    (options.includeRecord ? 1 : 0) + (options.attachmentIndices?.length || 0);

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center gap-2">
            <Printer className="w-5 h-5 text-primary-600" />
            <DialogTitle>{t("print.title") || "Print Options"}</DialogTitle>
          </div>
          <DialogDescription>
            {t("print.description") || "Select what you want to print"}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4 overflow-y-auto max-h-[calc(90vh-200px)]">
          {/* Record Section */}
          <div className="space-y-3">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="record"
                checked={options.includeRecord}
                onCheckedChange={handleRecordToggle}
              />
              <Label
                htmlFor="record"
                className="flex items-center gap-2 cursor-pointer font-medium"
              >
                <FileText className="w-4 h-4 text-blue-600" />
                {t("print.recordDocument") || "Record Document"}
              </Label>
            </div>
            <p className="text-sm text-muted-foreground ml-6">
              {t("print.recordDescription") || "Print the main record document"}
            </p>
          </div>

          <Separator />

          {/* Attachments Section */}
          <div className="space-y-3">
            {attachments.length > 0 ? (
              <>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="attachments"
                    checked={
                      options.includeAttachments &&
                      options.attachmentIndices?.length === attachments.length
                    }
                    onCheckedChange={handleAttachmentsToggle}
                  />
                  <Label
                    htmlFor="attachments"
                    className="flex items-center gap-2 cursor-pointer font-medium"
                  >
                    <Paperclip className="w-4 h-4 text-orange-600" />
                    {t("print.attachments") || "Attachments"} (
                    {attachments.length})
                  </Label>
                </div>

                {/* Individual Attachments */}
                {options.includeAttachments && (
                  <div className="ml-6 space-y-2 bg-muted/50 p-3 rounded-lg max-h-[200px] overflow-y-auto">
                    <TooltipProvider>
                      {attachments.map((attachment, index) => (
                        <div
                          key={attachment.id}
                          className="flex items-center space-x-2 min-w-0"
                        >
                          <Checkbox
                            id={`attachment-${index}`}
                            checked={
                              options.attachmentIndices?.includes(index) ||
                              false
                            }
                            onCheckedChange={(checked) =>
                              handleAttachmentToggle(index, checked as boolean)
                            }
                            className="flex-shrink-0"
                          />
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Label
                                htmlFor={`attachment-${index}`}
                                className="flex items-center gap-2 cursor-pointer text-sm flex-1 min-w-0 "
                              >
                                <span className="truncate">
                                  {attachment.name}
                                </span>
                                <span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0">
                                  ({(attachment.size / 1024).toFixed(1)} KB)
                                </span>
                              </Label>
                            </TooltipTrigger>
                            <TooltipContent
                              side="top"
                              className="max-w-xs break-words bg-primary-500 text-black border-primary-600"
                            >
                              <p className="font-medium text-black">
                                {attachment.name}
                              </p>
                              <p className="text-xs text-black/80 mt-1">
                                Size: {(attachment.size / 1024).toFixed(1)} KB
                              </p>
                            </TooltipContent>
                          </Tooltip>
                        </div>
                      ))}
                    </TooltipProvider>
                  </div>
                )}
              </>
            ) : (
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <AlertCircle className="w-4 h-4" />
                {t("print.noAttachments") || "No attachments available"}
              </div>
            )}
          </div>

          {/* Summary */}
          <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
            <p className="text-sm font-medium text-blue-900 dark:text-blue-100">
              {t("print.summary") || "Items to print"}: {selectedCount}
            </p>
            <p className="text-xs text-blue-700 dark:text-blue-200 mt-1">
              {selectedCount === 0
                ? t("print.selectAtLeastOne") ||
                  "Please select at least one item"
                : t("print.readyToPrint") || "Ready to print"}
            </p>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={onClose} disabled={isLoading}>
            {t("common.cancel") || "Cancel"}
          </Button>
          <Button
            onClick={handlePrint}
            disabled={isLoading || selectedCount === 0}
            className="bg-primary-600 hover:bg-primary-700"
          >
            {isLoading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                {t("print.printing") || "Printing..."}
              </>
            ) : (
              <>
                <Printer className="w-4 h-4 mr-2" />
                {t("print.print") || "Print"}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default PrintDialog;
