"use client"

import { useState, useEffect } from "react"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { ContractDetail } from "@/db/schema/contract"
import { getVendorContacts } from "../service"

// Type for vendor contact
interface VendorContact {
  id: number
  contactName: string
  contactEmail: string
  contactPosition: string | null
  isPrimary: boolean
}

// Form schema for signature request
const signatureRequestSchema = z.object({
  // Requester signer information
  includeRequesterSigner: z.boolean().default(true),
  requesterEmail: z.string().email("Please enter a valid email address").optional(),
  requesterName: z.string().min(1, "Please enter the signer's name").optional(),
  requesterPosition: z.string().optional(),
  
  // Vendor signer information
  includeVendorSigner: z.boolean().default(true),
  vendorContactId: z.number().optional(),
}).refine(data => data.includeRequesterSigner || data.includeVendorSigner, {
  message: "At least one signer must be included",
  path: ["includeRequesterSigner"]
}).refine(data => !data.includeRequesterSigner || (data.requesterEmail && data.requesterName), {
  message: "Requester email and name are required",
  path: ["requesterEmail"]
}).refine(data => !data.includeVendorSigner || data.vendorContactId, {
  message: "Please select a vendor contact",
  path: ["vendorContactId"]
});

type SignatureRequestFormValues = z.infer<typeof signatureRequestSchema>

// Interface for signing parties
interface SigningParty {
  signerEmail: string;
  signerName: string;
  signerPosition: string;
  signerType: "REQUESTER" | "VENDOR";
  vendorContactId?: number;
}

// Updated interface to accept multiple signers
interface SignatureRequestModalProps {
  contract: ContractDetail
  open: boolean
  onOpenChange: (open: boolean) => void
  onSubmit: (
    values: {
      signers: SigningParty[]
    }, 
    contractId: number
  ) => Promise<{ success: boolean; message: string } | void>
}

export function SignatureRequestModal({
  contract,
  open,
  onOpenChange,
  onSubmit,
}: SignatureRequestModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [vendorContacts, setVendorContacts] = useState<VendorContact[]>([])
  const [selectedVendorContact, setSelectedVendorContact] = useState<VendorContact | null>(null)

  const form = useForm<SignatureRequestFormValues>({
    resolver: zodResolver(signatureRequestSchema),
    defaultValues: {
      includeRequesterSigner: true,
      requesterEmail: "",
      requesterName: "",
      requesterPosition: "",
      includeVendorSigner: true,
      vendorContactId: undefined,
    },
  })

  // Load vendor contacts when the modal opens
  useEffect(() => {
    if (open && contract?.vendorId) {
      const loadVendorContacts = async () => {
        try {
          const contacts = await getVendorContacts(contract.vendorId);
          setVendorContacts(contacts);
          
          // Auto-select primary contact if available
          const primaryContact = contacts.find(c => c.isPrimary);
          if (primaryContact) {
            handleVendorContactSelect(primaryContact.id.toString());
          }
        } catch (error) {
          console.error("Error loading vendor contacts:", error);
          toast.error("Failed to load vendor contacts");
        }
      };
      
      loadVendorContacts();
    }
  }, [open, contract]);

  // Handle selection of a vendor contact
  const handleVendorContactSelect = (contactId: string) => {
    const id = Number(contactId);
    form.setValue("vendorContactId", id);
    
    // Find the selected contact to show details
    const contact = vendorContacts.find(c => c.id === id);
    if (contact) {
      setSelectedVendorContact(contact);
    }
  };

  async function handleSubmit(values: SignatureRequestFormValues) {
    setIsSubmitting(true);
    
    try {
      const signers: SigningParty[] = [];
      
      // Add requester signer if included
      if (values.includeRequesterSigner && values.requesterEmail && values.requesterName) {
        signers.push({
          signerEmail: values.requesterEmail,
          signerName: values.requesterName,
          signerPosition: values.requesterPosition || "",
          signerType: "REQUESTER"
        });
      }
      
      // Add vendor signer if included
      if (values.includeVendorSigner && values.vendorContactId && selectedVendorContact) {
        signers.push({
          signerEmail: selectedVendorContact.contactEmail,
          signerName: selectedVendorContact.contactName,
          signerPosition: selectedVendorContact.contactPosition || "",
          vendorContactId: values.vendorContactId,
          signerType: "VENDOR"
        });
      }
      
      if (signers.length === 0) {
        throw new Error("At least one signer must be included");
      }
      
      const result = await onSubmit({ signers }, contract.id);
      
      // Handle the result if it exists
      if (result && typeof result === 'object') {
        if (result.success) {
          toast.success(result.message || "Signature requests sent successfully");
        } else {
          toast.error(result.message || "Failed to send signature requests");
        }
      } else {
        // If no result is returned, assume success
        toast.success("Electronic signature requests sent successfully");
      }
      
      form.reset();
      onOpenChange(false);
    } catch (error) {
      console.error("Error sending signature requests:", error);
      toast.error(error instanceof Error ? error.message : "Failed to send signature requests. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>Request Electronic Signatures</DialogTitle>
          <DialogDescription>
            Send signature requests for contract: {contract?.contractName || ""}
          </DialogDescription>
        </DialogHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            <Accordion type="multiple" defaultValue={["requester", "vendor"]} className="w-full">
              {/* Requester Signature Section */}
              <AccordionItem value="requester">
                <div className="flex items-center space-x-2">
                  <FormField
                    control={form.control}
                    name="includeRequesterSigner"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center space-x-3 space-y-0 my-2">
                        <FormControl>
                          <Checkbox
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                        <AccordionTrigger className="hover:no-underline ml-2">
                          <div className="text-sm font-medium">Requester Signature</div>
                        </AccordionTrigger>
                      </FormItem>
                    )}
                  />
                </div>
                <AccordionContent>
                  {form.watch("includeRequesterSigner") && (
                    <Card className="border-none shadow-none">
                      <CardContent className="p-0 space-y-4">
                        <FormField
                          control={form.control}
                          name="requesterEmail"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Signer Email</FormLabel>
                              <FormControl>
                                <Input placeholder="email@example.com" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        
                        <FormField
                          control={form.control}
                          name="requesterName"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Signer Name</FormLabel>
                              <FormControl>
                                <Input placeholder="Full Name" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        
                        <FormField
                          control={form.control}
                          name="requesterPosition"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Signer Position</FormLabel>
                              <FormControl>
                                <Input placeholder="e.g. CEO, Manager" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </CardContent>
                    </Card>
                  )}
                </AccordionContent>
              </AccordionItem>
              
              {/* Vendor Signature Section */}
              <AccordionItem value="vendor">
                <div className="flex items-center space-x-2">
                  <FormField
                    control={form.control}
                    name="includeVendorSigner"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center space-x-3 space-y-0 my-2">
                        <FormControl>
                          <Checkbox
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                        <AccordionTrigger className="hover:no-underline ml-2">
                          <div className="text-sm font-medium">Vendor Signature</div>
                        </AccordionTrigger>
                      </FormItem>
                    )}
                  />
                </div>
                <AccordionContent>
                  {form.watch("includeVendorSigner") && (
                    <Card className="border-none shadow-none">
                      <CardContent className="p-0 space-y-4">
                        <FormField
                          control={form.control}
                          name="vendorContactId"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Select Vendor Contact</FormLabel>
                              <Select 
                                onValueChange={handleVendorContactSelect}
                                defaultValue={field.value?.toString()}
                              >
                                <FormControl>
                                  <SelectTrigger>
                                    <SelectValue placeholder="Select a contact" />
                                  </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  {vendorContacts.length > 0 ? (
                                    vendorContacts.map((contact) => (
                                      <SelectItem 
                                        key={contact.id} 
                                        value={contact.id.toString()}
                                      >
                                        {contact.contactName} {contact.isPrimary ? "(Primary)" : ""}
                                      </SelectItem>
                                    ))
                                  ) : (
                                    <SelectItem value="none" disabled>
                                      No contacts available
                                    </SelectItem>
                                  )}
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        
                        {/* Display selected contact info (read-only) */}
                        {selectedVendorContact && (
                          <>
                            <FormItem className="pb-2">
                              <FormLabel>Contact Email</FormLabel>
                              <div className="p-2 border rounded-md bg-muted">
                                {selectedVendorContact.contactEmail}
                              </div>
                            </FormItem>
                            
                            <FormItem className="pb-2">
                              <FormLabel>Contact Name</FormLabel>
                              <div className="p-2 border rounded-md bg-muted">
                                {selectedVendorContact.contactName}
                              </div>
                            </FormItem>
                            
                            <FormItem className="pb-2">
                              <FormLabel>Contact Position</FormLabel>
                              <div className="p-2 border rounded-md bg-muted">
                                {selectedVendorContact.contactPosition || "N/A"}
                              </div>
                            </FormItem>
                          </>
                        )}
                      </CardContent>
                    </Card>
                  )}
                </AccordionContent>
              </AccordionItem>
            </Accordion>
            
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? "Sending..." : "Send Requests"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}