import React, { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { FileText, Download, Calendar, User, ExternalLink, Tag, Trash2 } from 'lucide-react';
import { format } from 'date-fns';
import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { Separator } from '@/components/ui/separator';

export function BidQuoteDetailsDialog({ open, onOpenChange, bid, onRefresh }) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const { toast } = useToast();
  const { isAdmin } = useAuth();

  if (!bid) return null;

  const handleDelete = async () => {
    try {
        const { error } = await supabase.from('bids_quotes').delete().eq('id', bid.id);
        
        if (error) throw error;
        
        toast({ title: 'Deleted', description: 'Bid/Quote deleted successfully.' });
        setDeleteDialogOpen(false);
        onOpenChange(false);
        if (onRefresh) onRefresh();
    } catch (error) {
        console.error("Delete failed:", error);
        toast({ variant: 'destructive', title: 'Error', description: error.message || "Failed to delete bid." });
    }
  };

  return (
    <>
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden">
        <div className="p-6 pb-2 border-b">
           <DialogHeader>
             <div className="flex justify-between items-start gap-4">
                <div className="space-y-2">
                    <DialogTitle className="text-xl">{bid.title || bid.vendor_name}</DialogTitle>
                    <div className="flex items-center gap-3 text-sm text-muted-foreground">
                        <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {format(new Date(bid.created_at), 'MMM d, yyyy')}
                        </span>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {isAdmin && (
                        <Button 
                            variant="destructive" 
                            size="sm"
                            onClick={() => setDeleteDialogOpen(true)}
                        >
                            <Trash2 className="w-4 h-4 mr-2" />
                            Delete
                        </Button>
                    )}
                </div>
             </div>
           </DialogHeader>
        </div>

        <ScrollArea className="flex-1 p-6">
           <div className="space-y-6">
               <div className="prose max-w-none text-sm">
                   <h3 className="text-lg font-semibold mb-2">Description</h3>
                   <div className="whitespace-pre-wrap">{bid.description || "No description provided."}</div>
               </div>

               <div className="p-4 border rounded-lg">
                   <h3 className="font-semibold mb-2">Details</h3>
                   <div className="grid grid-cols-2 gap-4 text-sm">
                     <div><span className="text-muted-foreground">Vendor:</span> {bid.vendor_name}</div>
                     <div><span className="text-muted-foreground">Amount:</span> ${bid.amount?.toFixed(2)}</div>
                     <div><span className="text-muted-foreground">Status:</span> {bid.status}</div>
                     {bid.received_date && <div><span className="text-muted-foreground">Received:</span> {format(new Date(bid.received_date), 'MMM d, yyyy')}</div>}
                   </div>
               </div>
           </div>
        </ScrollArea>
      </DialogContent>
    </Dialog>

    <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
            <AlertDialogHeader>
                <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                <AlertDialogDescription>
                    This action cannot be undone. This will permanently delete this bid/quote.
                </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                    Delete Bid/Quote
                </AlertDialogAction>
            </AlertDialogFooter>
        </AlertDialogContent>
    </AlertDialog>
    </>
  );
}
