/**
 * New Price List Page
 * Create a new price list
 */

'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, useQueryClient } from '@tanstack/react-query';
import { pricingAPI } from '@/lib/api/pricing';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Input,
  Select,
} from '@/components/ui';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const priceListSchema = z.object({
  name: z.string().min(1, 'Name is required').max(200),
  code: z.string().min(1, 'Code is required').max(50),
  price_list_type: z.enum(['RETAIL', 'WHOLESALE', 'B2B', 'CUSTOMER_SPECIFIC'], {
    required_error: 'Price list type is required',
  }),
  currency: z.string().min(3).max(3).default('KES'),
  description: z.string().max(1000).optional(),
  is_default: z.boolean().default(false),
  active: z.boolean().default(true),
});

export default function NewPriceListPage() {
  const router = useRouter();
  const queryClient = useQueryClient();

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(priceListSchema),
    defaultValues: {
      name: '',
      code: '',
      price_list_type: 'RETAIL',
      currency: 'KES',
      description: '',
      is_default: false,
      active: true,
    },
  });

  // Create price list mutation
  const createPriceListMutation = useMutation({
    mutationFn: async (data) => {
      return await pricingAPI.createPriceList(data);
    },
    onSuccess: (response) => {
      const priceListId = response?.data?.id || response?.id;
      queryClient.invalidateQueries(['price-lists']);
      toast.success('Price list created successfully!');
      router.push(`/pricing/price-lists/${priceListId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create price list';
      toast.error(message);
    },
  });

  const onSubmit = (data) => {
    createPriceListMutation.mutate(data);
  };

  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.back()}
          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 Price List</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Create a new price list for products
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Form */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>Price List Information</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Input
                      label="Name"
                      type="text"
                      placeholder="e.g., Retail Prices"
                      {...register('name')}
                      error={errors.name?.message}
                      required
                    />
                  </div>
                  <div>
                    <Input
                      label="Code"
                      type="text"
                      placeholder="e.g., RETAIL-001"
                      {...register('code')}
                      error={errors.code?.message}
                      required
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Price List Type <span className="text-red-500">*</span>
                    </label>
                    <Select
                      {...register('price_list_type')}
                      error={errors.price_list_type?.message}
                    >
                      <option value="RETAIL">Retail</option>
                      <option value="WHOLESALE">Wholesale</option>
                      <option value="B2B">B2B</option>
                      <option value="CUSTOMER_SPECIFIC">Customer Specific</option>
                    </Select>
                  </div>
                  <div>
                    <Input
                      label="Currency"
                      type="text"
                      placeholder="KES"
                      maxLength={3}
                      {...register('currency')}
                      error={errors.currency?.message}
                    />
                  </div>
                </div>

                <div>
                  <Input
                    label="Description"
                    type="text"
                    placeholder="Optional description"
                    {...register('description')}
                    error={errors.description?.message}
                  />
                </div>

                <div className="flex items-center gap-6">
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      {...register('is_default')}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Set as default price list</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      {...register('active')}
                      defaultChecked
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Active</span>
                  </label>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Sidebar */}
          <div>
            <Card>
              <CardHeader>
                <CardTitle>Actions</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Button
                  type="submit"
                  variant="primary"
                  className="w-full"
                  disabled={createPriceListMutation.isLoading}
                  loading={createPriceListMutation.isLoading}
                >
                  Create Price List
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  className="w-full"
                  onClick={() => router.back()}
                >
                  Cancel
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </form>
    </div>
  );
}
