/**
 * New Production Order Page
 * Create a new production order
 */

'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { productionAPI } from '@/lib/api/production';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Input } from '@/components/ui';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const productionOrderSchema = z.object({
  fg_product_id: z.number().int().positive('Finished good product is required'), // Variants removed - use fg_product_id
  quantity: z.number().positive('Quantity must be positive'),
  status: z.enum(['DRAFT', 'CONFIRMED']).optional().default('DRAFT'),
});

export default function NewProductionOrderPage() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Fetch Finished Good products (FG type)
  const { data: fgProductsData } = useQuery({
    queryKey: ['products', 'FG'],
    queryFn: async () => {
      const response = await productsAPI.list({ product_type: 'FG', limit: 100 });
      return response?.data || response;
    },
  });

  const fgProducts = fgProductsData?.products || [];

  // Variants removed - use products directly

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(productionOrderSchema),
    defaultValues: {
      fg_product_id: undefined, // Variants removed - use fg_product_id
      quantity: 1,
      status: 'DRAFT',
    },
  });

  const selectedFgProductId = watch('fg_product_id');
  const selectedFgProduct = fgProducts.find((p) => p.id === parseInt(selectedFgProductId));

  const createProductionOrderMutation = useMutation({
    mutationFn: async (data) => {
      const orderData = {
        fg_product_id: parseInt(data.fg_product_id), // Variants removed - use fg_product_id
        quantity: parseFloat(data.quantity),
        status: data.status || 'DRAFT',
      };
      return await productionAPI.createProductionOrder(orderData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['production-orders']);
      toast.success('Production order created successfully!');
      router.push('/production/orders');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create production order';
      toast.error(message);
    },
  });

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

  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('/production/orders')}
          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">New Production Order</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create a new production order
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Production 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">
                  Finished Good Product <span className="text-red-500">*</span>
                </label>
                <select
                  {...register('fg_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.fg_product_id ? 'border-red-500' : 'border-gray-300'
                  }`}
                  required
                >
                  <option value="">Select finished good product...</option>
                  {fgProducts.map((product) => (
                    <option key={product.id} value={product.id}>
                      {product.name} {product.sku ? `(${product.sku})` : ''}
                    </option>
                  ))}
                </select>
                {errors.fg_product_id && (
                  <p className="mt-1 text-sm text-red-600 dark:text-red-400">{errors.fg_product_id.message}</p>
                )}
                {selectedFgProduct && (
                  <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    Producing: <strong>{selectedFgProduct.name}</strong>
                  </p>
                )}
              </div>

              <div>
                <Input
                  label="Quantity to Produce"
                  type="number"
                  step="0.01"
                  min="0.01"
                  {...register('quantity', { valueAsNumber: true })}
                  error={errors.quantity?.message}
                  required
                  placeholder="1"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Status
                </label>
                <select
                  {...register('status')}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="DRAFT">Draft</option>
                  <option value="CONFIRMED">Confirmed (will consume raw materials immediately)</option>
                </select>
                <p className="mt-1 text-xs text-gray-500">
                  Draft orders can be confirmed later. Confirmed orders immediately consume raw materials.
                </p>
              </div>
            </div>

            <div className="flex justify-end gap-4 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push('/production/orders')}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" variant="primary" disabled={isSubmitting} loading={isSubmitting}>
                Create Production Order
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

