/**
 * Edit Purchase Order Page
 * Edit an existing purchase order
 */

'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useForm, useFieldArray } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { procurementAPI } from '@/lib/api/procurement';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, LoadingSpinner } from '@/components/ui';
import { ArrowLeft, Plus, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatCurrency } from '@/lib/utils/format';

const purchaseOrderItemSchema = z.object({
  product_id: z.number().int().positive(),
  variant_id: z.number().int().positive().optional(),
  quantity: z.number().positive(),
  unit_cost: z.number().nonnegative(),
});

const purchaseOrderSchema = z.object({
  vendor_id: z.number().int().positive().optional(),
  status: z.enum(['DRAFT', 'CONFIRMED', 'CLOSED']).optional(),
  order_date: z.string().optional(),
  expected_delivery_date: z.string().optional(),
  items: z.array(purchaseOrderItemSchema).min(1, 'At least one item is required'),
  notes: z.string().optional(),
});

export default function EditPurchaseOrderPage() {
  const router = useRouter();
  const params = useParams();
  const poId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Fetch purchase order
  const { data: purchaseOrder, isLoading } = useQuery({
    queryKey: ['purchase-order', poId],
    queryFn: async () => {
      const response = await procurementAPI.getPurchaseOrder(poId);
      return response?.data || response;
    },
  });

  // Fetch vendors
  const { data: vendorsData } = useQuery({
    queryKey: ['vendors'],
    queryFn: async () => {
      const response = await procurementAPI.listVendors({ limit: 100 });
      return response.data || response;
    },
  });

  // Fetch products
  const { data: productsData } = useQuery({
    queryKey: ['products'],
    queryFn: async () => {
      const response = await productsAPI.list({ limit: 100 });
      return response.data || response;
    },
  });

  const vendors = vendorsData?.vendors || [];
  const products = productsData?.products || [];

  const {
    register,
    handleSubmit,
    control,
    watch,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(purchaseOrderSchema),
    values: purchaseOrder
      ? {
          vendor_id: purchaseOrder.vendor_id,
          status: purchaseOrder.status || 'DRAFT',
          order_date: purchaseOrder.order_date
            ? new Date(purchaseOrder.order_date).toISOString().split('T')[0]
            : undefined,
          expected_delivery_date: purchaseOrder.expected_delivery_date
            ? new Date(purchaseOrder.expected_delivery_date).toISOString().split('T')[0]
            : undefined,
          items:
            purchaseOrder.items?.map((item) => ({
              product_id: item.product_id,
              variant_id: item.variant_id || undefined,
              quantity: item.quantity,
              unit_cost: item.unit_cost,
            })) || [],
          notes: purchaseOrder.notes || '',
        }
      : undefined,
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items',
  });

  const watchedItems = watch('items');
  const calculateTotal = () => {
    return watchedItems?.reduce((sum, item) => {
      const quantity = parseFloat(item.quantity) || 0;
      const unitCost = parseFloat(item.unit_cost) || 0;
      return sum + quantity * unitCost;
    }, 0) || 0;
  };

  const updatePOMutation = useMutation({
    mutationFn: async (data) => {
      const poData = {
        ...(data.vendor_id && { vendor_id: parseInt(data.vendor_id) }),
        ...(data.status && { status: data.status }),
        ...(data.order_date && { order_date: data.order_date }),
        ...(data.expected_delivery_date && { expected_delivery_date: data.expected_delivery_date }),
        items: data.items.map((item) => ({
          product_id: parseInt(item.product_id),
          variant_id: item.variant_id ? parseInt(item.variant_id) : undefined,
          quantity: parseFloat(item.quantity),
          unit_cost: parseFloat(item.unit_cost),
        })),
        ...(data.notes && { notes: data.notes }),
      };
      return await procurementAPI.updatePurchaseOrder(poId, poData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['purchase-order', poId]);
      queryClient.invalidateQueries(['purchase-orders']);
      toast.success('Purchase order updated successfully!');
      router.push(`/procurement/purchase-orders/${poId}`);
    },
    onError: (error) => {
      const message =
        error?.response?.data?.message || error.message || 'Failed to update purchase order';
      toast.error(message);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      await updatePOMutation.mutateAsync(data);
    } catch (error) {
      // Error handled in mutation
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  if (!purchaseOrder) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">Purchase order not found</p>
              <Button onClick={() => router.push('/procurement/purchase-orders')} variant="outline">
                Back to Purchase Orders
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          onClick={() => router.push(`/procurement/purchase-orders/${poId}`)}
          className="flex items-center gap-2"
        >
          <ArrowLeft className="w-4 h-4" />
          Back
        </Button>
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Edit Purchase Order</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            PO #{purchaseOrder.po_number || purchaseOrder.id}
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Purchase Order Information</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Vendor</label>
                <select
                  {...register('vendor_id', { valueAsNumber: true })}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white"
                >
                  <option value="">Select vendor...</option>
                  {vendors.map((vendor) => (
                    <option key={vendor.id} value={vendor.id}>
                      {vendor.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Status</label>
                <select
                  {...register('status')}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white"
                >
                  <option value="DRAFT">Draft</option>
                  <option value="CONFIRMED">Confirmed</option>
                  <option value="CLOSED">Closed</option>
                </select>
              </div>

              <Input
                label="Order Date"
                type="date"
                {...register('order_date')}
                error={errors.order_date?.message}
              />

              <Input
                label="Expected Delivery Date"
                type="date"
                {...register('expected_delivery_date')}
                error={errors.expected_delivery_date?.message}
              />
            </div>

            {/* Items Section - Same as new form */}
            <div className="border-t dark:border-gray-700 pt-6">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Items</h3>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => append({ product_id: 0, quantity: 1, unit_cost: 0 })}
                  className="flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" />
                  Add Item
                </Button>
              </div>

              {fields.map((field, index) => (
                <div key={field.id} className="grid grid-cols-12 gap-4 mb-4 p-4 border dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800">
                  <div className="col-span-5">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Product <span className="text-red-500">*</span>
                    </label>
                    <select
                      {...register(`items.${index}.product_id`, { valueAsNumber: true })}
                      className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-900 dark:text-white dark:border-gray-600 ${
                        errors.items?.[index]?.product_id ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                      }`}
                      required
                    >
                      <option value="">Select product...</option>
                      {products.map((product) => (
                        <option key={product.id} value={product.id}>
                          {product.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="col-span-2">
                    <Input
                      label="Quantity"
                      type="number"
                      step="0.01"
                      min="0.01"
                      {...register(`items.${index}.quantity`, { valueAsNumber: true })}
                      error={errors.items?.[index]?.quantity?.message}
                      required
                    />
                  </div>

                  <div className="col-span-2">
                    <Input
                      label="Unit Cost"
                      type="number"
                      step="0.01"
                      min="0"
                      {...register(`items.${index}.unit_cost`, { valueAsNumber: true })}
                      error={errors.items?.[index]?.unit_cost?.message}
                      required
                    />
                  </div>

                  <div className="col-span-2 flex items-end">
                    <div className="w-full">
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Total</label>
                      <div className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white">
                        {formatCurrency(
                          (parseFloat(watchedItems?.[index]?.quantity) || 0) *
                            (parseFloat(watchedItems?.[index]?.unit_cost) || 0)
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="col-span-1 flex items-end">
                    {fields.length > 1 && (
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => remove(index)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                </div>
              ))}

              <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg flex justify-end">
                <div className="text-right">
                  <p className="text-sm text-gray-600 dark:text-gray-400">Total Amount:</p>
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">{formatCurrency(calculateTotal())}</p>
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-4 pt-4 border-t dark:border-gray-700">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push(`/procurement/purchase-orders/${poId}`)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" variant="primary" disabled={isSubmitting} loading={isSubmitting}>
                Update Purchase Order
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}


