import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { FileInput } from "@/components/ui/file-input";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { downloadFile, generateCsvTemplate } from "@/lib/utils";
import Papa from "papaparse";

export default function CSVUpload() {
  const { toast } = useToast();
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // CSV upload mutation
  const uploadMutation = useMutation({
    mutationFn: async (csvData: any[]) => {
      const response = await apiRequest('POST', '/api/jumps/bulk', csvData);
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "CSV Uploaded Successfully",
        description: `${data.jumps.length} jumps have been added to your logbook.`,
      });
      
      // Reset form
      setFile(null);
      setError(null);
      
      // Invalidate queries to refresh data
      queryClient.invalidateQueries({ queryKey: ['/api/jumps'] });
      queryClient.invalidateQueries({ queryKey: ['/api/stats'] });
      
      setIsUploading(false);
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: `Failed to process CSV: ${error instanceof Error ? error.message : 'Unknown error'}`,
        variant: "destructive",
      });
      setIsUploading(false);
    }
  });

  // Handle CSV template download
  const handleDownloadTemplate = () => {
    const template = generateCsvTemplate();
    downloadFile(template, 'skylog_template.csv', 'text/csv');
  };

  // Handle file upload
  const handleUpload = () => {
    if (!file) {
      setError("Please select a CSV file first");
      return;
    }

    setIsUploading(true);
    setError(null);

    // Parse CSV file
    Papa.parse(file, {
      header: true,
      complete: (results) => {
        if (results.errors.length > 0) {
          setError(`CSV parsing error: ${results.errors[0].message}`);
          setIsUploading(false);
          return;
        }

        // Check required headers
        const requiredHeaders = ['Jump Number', 'Type of Jump', 'DZ', 'Altitude', 'Aircraft', 'Equipment'];
        const missingHeaders = requiredHeaders.filter(
          header => !results.meta.fields?.includes(header)
        );

        if (missingHeaders.length > 0) {
          setError(`CSV is missing required columns: ${missingHeaders.join(', ')}`);
          setIsUploading(false);
          return;
        }

        // Submit data
        uploadMutation.mutate(results.data);
      },
      error: (error) => {
        setError(`Failed to parse CSV: ${error.message}`);
        setIsUploading(false);
      }
    });
  };

  return (
    <div className="space-y-6">
      <div className="mb-8">
        <p className="text-gray-700 mb-4">
          Upload a CSV file with your jump data. The file should have the following columns: 
          Jump Number, Type of Jump, DZ, Altitude, Aircraft, Equipment.
        </p>
        
        <Button 
          variant="link" 
          onClick={handleDownloadTemplate}
          className="text-[#3B82F6] p-0 flex items-center"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
          </svg>
          Download CSV Template
        </Button>
      </div>
      
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      
      <div className="space-y-4">
        <FileInput
          id="csv-file"
          accept=".csv"
          onFileChange={setFile}
        />
        
        <Button 
          onClick={handleUpload}
          className="bg-[#3B82F6] hover:bg-[#1E40AF] text-white"
          disabled={!file || isUploading}
        >
          {isUploading ? "Processing..." : "Upload and Process"}
        </Button>
      </div>
    </div>
  );
}
