/**
 * New Vendor Page
 * Create a new vendor
 */

'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 { procurementAPI } from '@/lib/api/procurement';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, Textarea } from '@/components/ui';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const vendorSchema = z.object({
  name: z.string().min(1, 'Vendor name is required').max(255),
  type: z.enum(['REGISTERED', 'OPEN_MARKET']).default('REGISTERED'),
  contact_person: z.string().optional(),
  email: z.string().email().optional().or(z.literal('')),
  phone: z.string().optional().or(z.literal('')),
  address: z.string().optional(),
  kra_pin: z.string().optional().or(z.literal('')),
  payment_terms: z.string().optional(),
  notes: z.string().optional(),
});

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

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(vendorSchema),
    defaultValues: {
      type: 'REGISTERED',
    },
  });

  const createVendorMutation = useMutation({
    mutationFn: async (data) => {
      const vendorData = {
        ...data,
        email: data.email === '' ? undefined : data.email,
        phone: data.phone === '' ? undefined : data.phone,
        kra_pin: data.kra_pin === '' ? undefined : data.kra_pin,
      };
      return await procurementAPI.createVendor(vendorData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['vendors']);
      toast.success('Vendor created successfully!');
      router.push('/procurement/vendors');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create vendor';
      toast.error(message);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      await createVendorMutation.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('/procurement/vendors')}
          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 Vendor</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create a new vendor/supplier
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Vendor Information</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Input
                label="Vendor Name"
                type="text"
                placeholder="Enter vendor name"
                {...register('name')}
                error={errors.name?.message}
                required
                autoFocus
              />

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Vendor Type <span className="text-red-500">*</span>
                </label>
                <select
                  {...register('type')}
                  className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.type ? 'border-red-500' : 'border-gray-300'
                  }`}
                  required
                >
                  <option value="REGISTERED">Registered</option>
                  <option value="OPEN_MARKET">Open Market</option>
                </select>
                {errors.type && (
                  <p className="mt-1 text-sm text-red-600">{errors.type.message}</p>
                )}
              </div>

              <Input
                label="Contact Person"
                type="text"
                placeholder="Contact person name (optional)"
                {...register('contact_person')}
                error={errors.contact_person?.message}
              />

              <Input
                label="Email"
                type="email"
                placeholder="vendor@example.com (optional)"
                {...register('email')}
                error={errors.email?.message}
              />

              <Input
                label="Phone"
                type="text"
                placeholder="Phone number (optional)"
                {...register('phone')}
                error={errors.phone?.message}
              />

              <Input
                label="KRA PIN"
                type="text"
                placeholder="KRA PIN (optional)"
                {...register('kra_pin')}
                error={errors.kra_pin?.message}
              />

              <Input
                label="Payment Terms"
                type="text"
                placeholder="Payment terms (optional)"
                {...register('payment_terms')}
                error={errors.payment_terms?.message}
              />
            </div>

            <Textarea
              label="Address"
              placeholder="Vendor address (optional)"
              rows={3}
              {...register('address')}
              error={errors.address?.message}
            />

            <Textarea
              label="Notes"
              placeholder="Additional notes (optional)"
              rows={3}
              {...register('notes')}
              error={errors.notes?.message}
            />

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

