"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Upload, Download, X, Loader, FileSpreadsheet } from "lucide-react";
import { downloadCustomerTemplate } from "@/lib/generateCustomerTemplate";
import Axios from "@/lib/Axios";
import { toast } from "@/components/ui/use-toast";

interface ImportCustomersDialogProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void; // Callback to refresh table
}

export function ImportCustomersDialog({
  open,
  onClose,
  onSuccess,
}: ImportCustomersDialogProps) {
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile) {
      // Validate file type
      const validExtensions = ['.xlsx', '.xls'];
      const fileExtension = selectedFile.name
        .substring(selectedFile.name.lastIndexOf('.'))
        .toLowerCase();

      if (!validExtensions.includes(fileExtension)) {
        toast({
          variant: "destructive",
          title: "Invalid File Type",
          description: "Please select an Excel file (.xlsx or .xls)",
        });
        return;
      }

      // Validate file size (5MB limit)
      if (selectedFile.size > 5 * 1024 * 1024) {
        toast({
          variant: "destructive",
          title: "File Too Large",
          description: "File size must be less than 5MB",
        });
        return;
      }

      setFile(selectedFile);
    }
  };

  const handleDownloadTemplate = () => {
    try {
      downloadCustomerTemplate();
      toast({
        title: "Template Downloaded",
        description: "Excel template has been downloaded. Fill it with your customer data.",
      });
    } catch (error) {
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to download template. Please try again.",
      });
    }
  };

  const handleUpload = async () => {
    if (!file) {
      toast({
        variant: "destructive",
        title: "No File Selected",
        description: "Please select an Excel file to upload",
      });
      return;
    }

    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await Axios.post('/customer/management/bulk', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.success) {
        const details = response.data.data?.details || {};
        const duplicateIds = details.duplicateIds || [];
        
        // Show success message first
        toast({
          title: "Import Successful!",
          description: response.data.message || "Customers imported successfully",
        });

        // If there are duplicate IDs, show them in a separate message after a short delay
        if (duplicateIds.length > 0) {
          setTimeout(() => {
            const duplicateMessage = duplicateIds.length <= 5
              ? `The following Customer IDs were not imported (duplicate mobile_phone, home_phone, or email): ${duplicateIds.join(', ')}`
              : `${duplicateIds.length} records were skipped due to duplicates (mobile_phone, home_phone, or email already exist). First 5 IDs: ${duplicateIds.slice(0, 5).join(', ')}...`;
            
            toast({
              variant: "default",
              title: "Duplicate Records Skipped",
              description: duplicateMessage,
              duration: 12000, // Show for 12 seconds
            });
          }, 1500);
        }

        // Reset form
        setFile(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }

        // Close dialog
        onClose();

        // Refresh table
        onSuccess();
      }
    } catch (error: any) {
      console.error('Upload error:', error);
      
      let errorMessage = "Failed to import customers. Please try again.";
      
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.message) {
        errorMessage = error.message;
      }

      toast({
        variant: "destructive",
        title: "Import Failed",
        description: errorMessage,
      });
    } finally {
      setIsUploading(false);
    }
  };

  const handleClose = () => {
    if (!isUploading) {
      setFile(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
      onClose();
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px] max-w-[calc(100vw-2rem)] overflow-hidden">
        <DialogHeader>
          <DialogTitle>Import Customers from Excel</DialogTitle>
          <DialogDescription>
            Upload an Excel file to import multiple customers at once. Download the template to see the required format.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4 overflow-x-hidden">
          {/* Download Template Section */}
          <div className="border rounded-lg p-4 space-y-2 overflow-hidden">
            <div className="flex items-start justify-between gap-3">
              <div className="flex-1 min-w-0">
                <h4 className="font-medium">Step 1: Download Template</h4>
                <p className="text-sm text-gray-600 break-words">
                  Get the Excel template with required column headers
                </p>
              </div>
              <Button
                type="button"
                variant="outline"
                onClick={handleDownloadTemplate}
                className="flex items-center gap-2 flex-shrink-0"
              >
                <Download className="w-4 h-4" />
                <span className="hidden sm:inline">Download Template</span>
                <span className="sm:hidden">Download</span>
              </Button>
            </div>
          </div>

          {/* Upload File Section */}
          <div className="border rounded-lg p-4 space-y-3 overflow-hidden">
            <div className="min-w-0">
              <h4 className="font-medium">Step 2: Upload Excel File</h4>
              <p className="text-sm text-gray-600 break-words">
                Select your filled Excel file (.xlsx or .xls)
              </p>
            </div>
            
            <div className="space-y-3 overflow-hidden">
              <input
                ref={fileInputRef}
                type="file"
                accept=".xlsx,.xls"
                onChange={handleFileSelect}
                className="hidden"
                id="file-upload"
                disabled={isUploading}
              />
              <label htmlFor="file-upload" className="block">
                <Button
                  type="button"
                  variant="outline"
                  asChild
                  disabled={isUploading}
                  className="cursor-pointer"
                >
                  <span className="flex items-center gap-2">
                    <Upload className="w-4 h-4 flex-shrink-0" />
                    Choose File
                  </span>
                </Button>
              </label>
              
              {file && (
                <div className="mt-2 border border-gray-200 dark:border-gray-700 rounded-lg p-3 bg-gray-50 dark:bg-gray-900/40 overflow-hidden">
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="flex-shrink-0">
                      <div className="w-10 h-10 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center border border-green-200 dark:border-green-800">
                        <FileSpreadsheet className="w-6 h-6 text-green-600 dark:text-green-400" />
                      </div>
                    </div>
                    <div className="flex-1 min-w-0 overflow-hidden">
                      <div className="flex items-start justify-between gap-2 min-w-0">
                        <div className="flex-1 min-w-0 overflow-hidden">
                          <p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate mb-1" title={file.name}>
                            {file.name}
                          </p>
                          <p className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
                            Size: {(file.size / 1024).toFixed(2)} KB
                          </p>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setFile(null);
                            if (fileInputRef.current) {
                              fileInputRef.current.value = '';
                            }
                          }}
                          disabled={isUploading}
                          className="h-8 w-8 p-0 flex-shrink-0 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md"
                        >
                          <X className="w-4 h-4 text-gray-400 hover:text-red-600 dark:hover:text-red-400" />
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Instructions */}
          <div className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg p-3 overflow-hidden">
            <h5 className="font-medium text-sm mb-2">Important Notes:</h5>
            <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-1 list-disc list-inside break-words">
              <li>First row must contain headers (id, first_name, last_name, etc.)</li>
              <li>first_name and last_name are required fields</li>
              <li>Numbers must be unique</li>
              <li>Address fields are optional but recommended</li>
              {/* <li>Format phone columns as TEXT to avoid scientific notation</li> */}
              <li>Maximum file size: 5MB</li>
            </ul>
          </div>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleClose}
            disabled={isUploading}
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={handleUpload}
            disabled={!file || isUploading}
            className="bg-brownish hover:bg-yellowish"
          >
            {isUploading ? (
              <>
                <Loader className="w-4 h-4 mr-2 animate-spin" />
                Uploading...
              </>
            ) : (
              <>
                <Upload className="w-4 h-4 mr-2" />
                Import Customers
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

