
"use client";

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { FileSpreadsheet, UploadCloud, Loader2, Download, Trash2, LogIn, FolderOutput } from 'lucide-react';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { downloadCsv } from '@/lib/csvUtils';
import { useToast } from '@/hooks/use-toast';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

interface ActionsSectionProps {
  onGenerateCsv: () => Promise<string>;
  onClearAllData: () => void;
  isProcessing: boolean; // Generic processing state from parent for CSV generation
  csvPreview: string | null;
  hasData: boolean;
}

export function ActionsSection({
  onGenerateCsv,
  onClearAllData,
  isProcessing: parentIsProcessing,
  csvPreview,
  hasData,
}: ActionsSectionProps) {
  const [csvProcessing, setCsvProcessing] = useState(false);
  const [uploadingOneDrive, setUploadingOneDrive] = useState(false);
  const [oneDriveUploadStatus, setOneDriveUploadStatus] = useState<{success: boolean, message: string, url?: string} | null>(null);
  const [oneDriveFolderPath, setOneDriveFolderPath] = useState<string>('counts/files_temp'); // Default path
  const { toast } = useToast();
  
  useEffect(() => {
    const queryParams = new URLSearchParams(window.location.search);
    const oauthError = queryParams.get('error');
    if (oauthError) {
      let friendlyError = "Authentication failed.";
      if (oauthError === 'microsoft_config_error') friendlyError = "Microsoft authentication is not configured correctly.";
      if (oauthError === 'microsoft_auth_missing_code') friendlyError = "Microsoft authentication callback was missing necessary information.";
      if (oauthError === 'microsoft_token_exchange_failed') friendlyError = "Failed to get authentication token from Microsoft.";
      
      toast({
        variant: "destructive",
        title: "Microsoft Auth Error",
        description: friendlyError,
      });
      window.history.replaceState({}, document.title, window.location.pathname); // Clear error from URL
    }
  }, [toast]);


  const handleGenerate = async () => {
    setCsvProcessing(true);
    setOneDriveUploadStatus(null); 
    await onGenerateCsv();
    setCsvProcessing(false);
  };

  const handleDownload = () => {
    if (csvPreview) {
      const now = new Date();
      const datePart = now.toISOString().split('T')[0];
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const timePart = `${hours}${minutes}`;
      const fileName = `breakdown_export_${datePart}_${timePart}.csv`;
      downloadCsv(csvPreview, fileName);
    }
  };
  
  const handleUploadToOneDriveDirect = async () => {
    if (!csvPreview) {
      toast({ title: "Missing CSV", description: "Please generate the CSV first.", variant: "default" });
      return;
    }
    setUploadingOneDrive(true);
    setOneDriveUploadStatus(null);
    try {
      const now = new Date();
      const datePart = now.toISOString().split('T')[0];
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const timePart = `${hours}${minutes}`;
      const fileName = `breakdown_export_${datePart}_${timePart}.csv`;

      const response = await fetch('/api/onedrive/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          csvContent: csvPreview, 
          fileName: fileName,
          folderPath: oneDriveFolderPath 
        }),
      });
      const result = await response.json();

      if (!response.ok) {
        if (result.needsReAuth) {
          setOneDriveUploadStatus({ success: false, message: result.error || "Authentication required. Please login with Microsoft."});
          window.location.href = '/api/auth/microsoft/login';
        } else {
          throw new Error(result.error || `Upload failed (status: ${response.status})`);
        }
        return; 
      }
      setOneDriveUploadStatus({ success: result.success, message: result.message, url: result.url });
      toast({
        title: result.success ? "Upload Successful" : "Upload Failed",
        description: result.message,
        variant: result.success ? "default" : "destructive",
      });

    } catch (error: any) {
      setOneDriveUploadStatus({ success: false, message: error.message || "An unknown error occurred during upload." });
      toast({ variant: "destructive", title: "OneDrive Upload Error", description: error.message || "An unknown error occurred." });
    } finally {
      setUploadingOneDrive(false);
    }
  };

  const handleClearDataConfirmed = () => {
    setOneDriveUploadStatus(null); 
    onClearAllData();
  };

  const effectiveIsProcessing = parentIsProcessing || csvProcessing || uploadingOneDrive;

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <Button onClick={handleGenerate} disabled={effectiveIsProcessing || !hasData} className="w-full">
          {csvProcessing ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <FileSpreadsheet className="mr-2 h-4 w-4" />
          )}
          Generate CSV
        </Button>
        
        <Button onClick={handleUploadToOneDriveDirect} disabled={effectiveIsProcessing || !csvPreview || !hasData} className="w-full">
          {uploadingOneDrive ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <UploadCloud className="mr-2 h-4 w-4" />
          )}
          Upload to OneDrive
        </Button>

        <AlertDialog>
          <AlertDialogTrigger asChild>
            <Button variant="destructive" disabled={effectiveIsProcessing || !hasData} className="w-full">
              <Trash2 className="mr-2 h-4 w-4" />
              Clear All Data
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
              <AlertDialogDescription>
                This action will permanently delete all collected data for the Breakdown tool from your browser.
                This data cannot be recovered.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={handleClearDataConfirmed} className="bg-destructive hover:bg-destructive/90">
                Yes, clear all data
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>

      {hasData && (
        <div className="space-y-2">
            <Label htmlFor="oneDriveFolderPath" className="flex items-center gap-2">
                <FolderOutput size={16} /> OneDrive Folder Path (Optional)
            </Label>
            <Input
                id="oneDriveFolderPath"
                type="text"
                value={oneDriveFolderPath}
                onChange={(e) => setOneDriveFolderPath(e.target.value)}
                placeholder="e.g., My Reports/2024 or counts/files_temp"
                className="bg-background"
                disabled={effectiveIsProcessing || !csvPreview}
            />
        </div>
      )}

      {!hasData && (
         <p className="text-sm text-muted-foreground text-center">Add data to enable CSV generation, upload, and clearing.</p>
      )}

      {csvPreview && hasData && (
        <Card className="mt-4 bg-muted/30">
          <CardHeader>
            <CardTitle className="text-lg">CSV Preview</CardTitle>
            <CardDescription>Preview of the CSV. Download it or upload to OneDrive.</CardDescription>
          </CardHeader>
          <CardContent>
            <Textarea
              value={csvPreview}
              readOnly
              rows={8}
              className="text-xs font-mono bg-background"
              placeholder="CSV data will appear here..."
            />
          </CardContent>
          <CardFooter>
            <Button onClick={handleDownload} variant="outline" className="w-full">
              <Download className="mr-2 h-4 w-4" /> Download CSV
            </Button>
          </CardFooter>
        </Card>
      )}
      
      {oneDriveUploadStatus && (
        <div className={`mt-4 p-3 rounded-md text-sm ${oneDriveUploadStatus.success ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'}`}>
          <p>{oneDriveUploadStatus.message}</p>
          {oneDriveUploadStatus.url && (
            <a href={oneDriveUploadStatus.url} target="_blank" rel="noopener noreferrer" className="underline font-medium">
              View file on OneDrive
            </a>
          )}
           {oneDriveUploadStatus.success === false && oneDriveUploadStatus.message.includes("Authentication required") && (
             <Button onClick={() => window.location.href = '/api/auth/microsoft/login'} variant="link" className="p-0 h-auto text-sm">
                <LogIn className="mr-2 h-4 w-4" /> Login with Microsoft to retry
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
