
'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useToast } from '@/hooks/use-toast';
import { parcelSchema, type ParcelFormValues, type BookingResult } from '@/lib/types';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogClose,
} 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Loader2, Printer } from 'lucide-react';
import type { ReactNode } from 'react';
import { format } from 'date-fns';

interface BookParcelDialogProps {
  children: ReactNode;
  onBookingComplete: (result: BookingResult) => void;
  bookParcelAction: (values: ParcelFormValues) => Promise<BookingResult>;
}

export function BookParcelDialog({ children, onBookingComplete, bookParcelAction }: BookParcelDialogProps) {
  const [open, setOpen] = useState(false);
  const { toast } = useToast();

  const form = useForm<ParcelFormValues>({
    resolver: zodResolver(parcelSchema),
    defaultValues: {
      orderType: 'Normal',
      orderReferenceNumber: '',
      orderAmount: 0,
      orderDate: format(new Date(), 'yyyy-MM-dd'),
      customerName: '',
      customerContact: '',
      deliveryCity: 'Anytown',
      deliveryAddress: '',
      airwayBillCopies: 1,
      items: 1,
      pickupCity: 'MULTAN',
      pickupAddress: 'Main Office',
      returnCity: 'MULTAN',
      returnAddress: 'Main Office',
      bookingWeight: 0.5,
      orderDetail: '',
      notes: '',
      zone: 'A',
    },
  });

  const { isSubmitting } = form.formState;

  async function handleFormSubmit(values: ParcelFormValues, andPrint: boolean = false) {
    try {
      const result = await bookParcelAction(values);
      
      onBookingComplete(result);
      form.reset();
      setOpen(false);
      toast({
        title: 'Parcel Booked!',
        description: `Parcel ID: ${result?.parcel.id} has been successfully booked.`,
      });

      if (andPrint) {
        // In a real app, you would trigger a print action here.
        console.log("Printing parcel...", result?.parcel.id);
         toast({
            title: 'Printing...',
            description: `Preparing to print details for Parcel ID: ${result?.parcel.id}.`,
        });
      }

    } catch (error) {
      console.error("Booking failed", error)
      toast({
        variant: 'destructive',
        title: 'Booking Failed',
        description: 'An unexpected error occurred. Please try again.',
      });
    }
  }
  
  const onSubmit = (values: ParcelFormValues) => handleFormSubmit(values, false);
  const onSaveAndPrint = (values: ParcelFormValues) => handleFormSubmit(values, true);


  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {children}
      </DialogTrigger>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Create Order</DialogTitle>
          <DialogDescription>
            Fill in the details below to book a new parcel for delivery.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex-1 min-h-0 flex flex-col">
            <div className="flex-1 overflow-y-auto pr-4 -mr-4 space-y-4 py-2">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="orderType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Order Type</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl>
                              <SelectTrigger><SelectValue /></SelectTrigger>
                          </FormControl>
                          <SelectContent>
                              <SelectItem value="Normal">Normal</SelectItem>
                              <SelectItem value="Express">Express</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="orderReferenceNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Order Reference Number</FormLabel>
                      <FormControl><Input placeholder="Order ref Number" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="orderAmount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Order Amount</FormLabel>
                      <FormControl><Input type="number" placeholder="0" {...field} onChange={e => field.onChange(e.target.valueAsNumber)} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                 <FormField
                  control={form.control}
                  name="orderDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Order Date</FormLabel>
                      <FormControl><Input type="date" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="customerName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Customer Name</FormLabel>
                      <FormControl><Input placeholder="Customer Name" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="customerContact"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Customer Contact</FormLabel>
                      <FormControl><Input placeholder="03xxxxxxxx" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="deliveryCity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Delivery City</FormLabel>
                       <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl><SelectTrigger><SelectValue placeholder="Search"/></SelectTrigger></FormControl>
                          <SelectContent>
                              <SelectItem value="Anytown">Anytown</SelectItem>
                              <SelectItem value="Otherville">Otherville</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                 <FormField
                  control={form.control}
                  name="deliveryAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Delivery Address</FormLabel>
                      <FormControl><Input placeholder="Customer Address" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="airwayBillCopies"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Airway Bill Copies</FormLabel>
                      <FormControl><Input type="number" {...field} onChange={e => field.onChange(e.target.valueAsNumber)} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="items"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Items</FormLabel>
                      <FormControl><Input type="number" {...field} onChange={e => field.onChange(e.target.valueAsNumber)} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                 <FormField
                  control={form.control}
                  name="pickupCity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Pickup City</FormLabel>
                       <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                          <SelectContent>
                              <SelectItem value="MULTAN">MULTAN</SelectItem>
                              <SelectItem value="Otherville">Otherville</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                  <FormField
                  control={form.control}
                  name="pickupAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Pickup Address</FormLabel>
                       <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl><SelectTrigger><SelectValue placeholder="Search"/></SelectTrigger></FormControl>
                          <SelectContent>
                              <SelectItem value="Main Office">Main Office</SelectItem>
                              <SelectItem value="Warehouse A">Warehouse A</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                 <FormField
                  control={form.control}
                  name="returnCity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Return City</FormLabel>
                       <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl><SelectTrigger><SelectValue placeholder="Search"/></SelectTrigger></FormControl>
                          <SelectContent>
                             <SelectItem value="MULTAN">MULTAN</SelectItem>
                             <SelectItem value="Anytown">Anytown</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                 <FormField
                  control={form.control}
                  name="returnAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Return Address</FormLabel>
                       <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl><SelectTrigger><SelectValue placeholder="Search"/></SelectTrigger></FormControl>
                          <SelectContent>
                             <SelectItem value="Main Office">Main Office</SelectItem>
                             <SelectItem value="Warehouse A">Warehouse A</SelectItem>
                          </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="bookingWeight"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Booking Weight (kg)</FormLabel>
                      <FormControl><Input type="number" step="0.1" placeholder="Booking weight in Kg" {...field} onChange={e => field.onChange(e.target.valueAsNumber)} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="zone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Zone</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Select a delivery zone" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="A">Zone A</SelectItem>
                          <SelectItem value="B">Zone B</SelectItem>
                          <SelectItem value="C">Zone C</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="md:col-span-2">
                  <FormField
                      control={form.control}
                      name="orderDetail"
                      render={({ field }) => (
                      <FormItem>
                          <FormLabel>Order Detail (optional)</FormLabel>
                          <FormControl><Textarea placeholder="Details about the order..." {...field} /></FormControl>
                          <FormMessage />
                      </FormItem>
                      )}
                  />
                </div>

                 <div className="md:col-span-2">
                   <FormField
                      control={form.control}
                      name="notes"
                      render={({ field }) => (
                      <FormItem>
                          <FormLabel>Notes (optional)</FormLabel>
                          <FormControl><Textarea placeholder="Special instructions for delivery..." {...field} /></FormControl>
                          <FormMessage />
                      </FormItem>
                      )}
                  />
                </div>
              </div>
            </div>

            <DialogFooter className="mt-4 pt-4 border-t gap-2 sm:gap-0">
                <Button type="submit" variant="accent" disabled={isSubmitting}>
                    {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Save
                </Button>
                <Button type="button" variant="default" onClick={form.handleSubmit(onSaveAndPrint)} disabled={isSubmitting}>
                     {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                     <Printer className="mr-2" />
                    Save & Print
                </Button>
                <DialogClose asChild>
                    <Button type="button" variant="destructive">
                    Close
                    </Button>
              </DialogClose>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
