import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Upload, X } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';

const formSchema = z.object({
  vendor_name: z.string().min(2, 'Vendor name is required'),
  description: z.string().optional(),
  amount: z.coerce.number().min(0, 'Amount must be positive').optional(),
});

export function BidQuoteDialog({ open, onOpenChange, onSuccess }) {
  const [associations, setAssociations] = useState([]);
  const [selectedAssociations, setSelectedAssociations] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [fileUploading, setFileUploading] = useState(false);
  const [documentUrl, setDocumentUrl] = useState('');
  const [documentName, setDocumentName] = useState('');
  const { user } = useAuth();
  const { toast } = useToast();

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      vendor_name: '',
      description: '',
      amount: '',
    },
  });

  useEffect(() => {
    if (open) {
      fetchAssociations();
      form.reset();
      setSelectedAssociations([]);
      setDocumentUrl('');
      setDocumentName('');
    }
  }, [open, form]);

  const handleFileUpload = async (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    if (f.type !== 'application/pdf') {
      toast({ variant: 'destructive', title: 'PDF only', description: 'Please upload a PDF file.' });
      return;
    }
    setFileUploading(true);
    try {
      const path = `${user?.id || 'anon'}/${Date.now()}-${f.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
      const { error } = await supabase.storage.from('bid-attachments').upload(path, f, { upsert: true });
      if (error) throw error;
      const { data } = supabase.storage.from('bid-attachments').getPublicUrl(path);
      setDocumentUrl(data.publicUrl);
      setDocumentName(f.name);
      toast({ title: 'PDF attached', description: f.name });
    } catch (err) {
      toast({ variant: 'destructive', title: 'Upload failed', description: err.message });
    } finally {
      setFileUploading(false);
    }
  };

  const fetchAssociations = async () => {
    try {
      const { data, error } = await supabase
        .from('associations')
        .select('id, name')
        .order('name');
      
      if (error) throw error;
      setAssociations(data || []);
    } catch (error) {
      console.error('Error fetching associations:', error);
    }
  };

  const onSubmit = async (values) => {
    if (selectedAssociations.length === 0) {
      toast({
        variant: "destructive",
        title: "Validation Error",
        description: "Please select at least one association.",
      });
      return;
    }

    setUploading(true);
    try {
      // Create one bid per selected association
      const inserts = selectedAssociations.map(assocId => ({
        vendor_name: values.vendor_name,
        description: values.description,
        amount: values.amount || 0,
        association_id: assocId,
        created_by: user?.id,
        status: 'pending',
        document_url: documentUrl || null,
        document_name: documentName || null,
      }));

      const { error } = await supabase.from('bids_quotes').insert(inserts);
      if (error) throw error;

      toast({
        title: "Success",
        description: "Bid/Quote created successfully.",
      });
      
      onSuccess?.();
      onOpenChange(false);

    } catch (error) {
      console.error('Error creating bid:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message || "Failed to create bid/quote.",
      });
    } finally {
      setUploading(false);
    }
  };

  const toggleAssociation = (id) => {
    setSelectedAssociations(prev => 
      prev.includes(id) 
        ? prev.filter(x => x !== id)
        : [...prev, id]
    );
  };

  const selectAll = () => {
    if (selectedAssociations.length === associations.length) {
      setSelectedAssociations([]);
    } else {
      setSelectedAssociations(associations.map(c => c.id));
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Create New Bid / Quote</DialogTitle>
          <DialogDescription>
            Create a new bid or quote for review by association members.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 flex-1 overflow-y-auto pr-2">
            <FormField
              control={form.control}
              name="vendor_name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Vendor Name</FormLabel>
                  <FormControl>
                    <Input placeholder="e.g. ABC Landscaping" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="amount"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Amount</FormLabel>
                  <FormControl>
                    <Input type="number" step="0.01" placeholder="0.00" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="Enter details about this bid..." 
                      className="min-h-[100px]" 
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="space-y-2">
              <FormLabel>Attachment (PDF)</FormLabel>
              {documentName ? (
                <div className="flex items-center gap-3 p-3 border rounded-md bg-muted/30">
                  <a href={documentUrl} target="_blank" rel="noreferrer" className="text-sm text-primary underline truncate flex-1">
                    {documentName}
                  </a>
                  <Button type="button" variant="ghost" size="sm" className="gap-1 text-destructive"
                    onClick={() => { setDocumentUrl(''); setDocumentName(''); }}>
                    <X className="h-4 w-4" /> Remove
                  </Button>
                </div>
              ) : (
                <label className="inline-flex items-center gap-2 px-3 py-2 border rounded-md cursor-pointer hover:bg-muted text-sm">
                  {fileUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
                  {fileUploading ? 'Uploading…' : 'Upload PDF'}
                  <input type="file" accept="application/pdf" className="hidden" onChange={handleFileUpload} />
                </label>
              )}
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <FormLabel>Assign to Associations</FormLabel>
                <Button 
                    type="button" 
                    variant="ghost" 
                    size="sm" 
                    className="h-auto p-0 text-xs text-primary"
                    onClick={selectAll}
                >
                    {selectedAssociations.length === associations.length ? 'Deselect All' : 'Select All'}
                </Button>
              </div>
              <ScrollArea className="h-[200px] border rounded-md p-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {associations.map((assoc) => (
                    <div key={assoc.id} className="flex items-center space-x-2">
                      <Checkbox 
                        id={`assoc-${assoc.id}`} 
                        checked={selectedAssociations.includes(assoc.id)}
                        onCheckedChange={() => toggleAssociation(assoc.id)}
                      />
                      <label 
                        htmlFor={`assoc-${assoc.id}`} 
                        className="text-sm leading-none cursor-pointer"
                      >
                        {assoc.name}
                      </label>
                    </div>
                  ))}
                </div>
              </ScrollArea>
              <p className="text-xs text-muted-foreground">
                Selected: {selectedAssociations.length} associations
              </p>
            </div>
            
            <DialogFooter className="pt-4">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={uploading || fileUploading}>
                {uploading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Creating...
                  </>
                ) : (
                  'Create Bid'
                )}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
