/**
 * Edit Vendor Page
 * Edit an existing vendor
 */

'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useForm } 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 { Button, Card, CardHeader, CardTitle, CardContent, Input, Textarea, LoadingSpinner } 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']).optional(),
  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(),
  active: z.boolean().optional(),
});

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

  // Fetch vendor data
  const { data: vendor, isLoading } = useQuery({
    queryKey: ['vendor', vendorId],
    queryFn: async () => {
      const response = await procurementAPI.getVendor(vendorId);
      return response?.data || response;
    },
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(vendorSchema),
    values: vendor ? {
      name: vendor.name || '',
      type: vendor.type || vendor.vendor_type || 'REGISTERED',
      contact_person: vendor.contact_person || '',
      email: vendor.email || '',
      phone: vendor.phone || '',
      address: vendor.address || '',
      kra_pin: vendor.kra_pin || '',
      payment_terms: vendor.payment_terms || '',
      notes: vendor.notes || '',
      active: vendor.active !== false,
    } : undefined,
  });

  const updateVendorMutation = 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.updateVendor(vendorId, vendorData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['vendor', vendorId]);
      queryClient.invalidateQueries(['vendors']);
      toast.success('Vendor updated successfully!');
      router.push(`/procurement/vendors/${vendorId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update vendor';
      toast.error(message);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      await updateVendorMutation.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 (!vendor) {
    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">Vendor not found</p>
              <Button onClick={() => router.push('/procurement/vendors')} variant="outline">
                Back to Vendors
              </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/vendors/${vendorId}`)}
          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 Vendor</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {vendor.name}
          </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
              />

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Vendor Type
                </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'
                  }`}
                >
                  <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>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Status
                </label>
                <input
                  type="checkbox"
                  {...register('active')}
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-600">Active</span>
              </div>
            </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/${vendorId}`)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                disabled={isSubmitting}
                loading={isSubmitting}
              >
                Update Vendor
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

