'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import axiosInstance from '../../api/axiosInstance';

const CreateReference = ({ setAlert, idHouses, setIdHouses }) => {
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState({
    titleUz: '',
    titleRu: '',
    shortDescriptionUz: '',
    shortDescriptionRu: '',
    price: 0,
    exchange: 'USD',
    unit: '',
    unitValue: 1,
    cargoType: 'AVIA',
  });

  const resetForm = () => {
    setFormData({
      titleUz: '',
      titleRu: '',
      shortDescriptionUz: '',
      shortDescriptionRu: '',
      price: 0,
      exchange: 'USD',
      unit: '',
      unitValue: 1,
      cargoType: '',
    });
  };

  const { data, refetch } = useQuery({
    queryKey: ['warhouses_one'],
    queryFn: async () => {
      return await axiosInstance.get(`/cargo-reference-book/${idHouses}`);
    },
    enabled: !!idHouses,
    select(data) {
      return data.data;
    },
  });

  useEffect(() => {
    if (idHouses !== null) {
      refetch();
    }
  }, [idHouses]);

  useEffect(() => {
    if (data) {
      setFormData({
        cargoType: data.cargoType,
        exchange: data.exchange,
        price: data.price,
        shortDescriptionRu: data.shortDescriptionRu,
        shortDescriptionUz: data.shortDescriptionUz,
        titleRu: data.titleRu,
        titleUz: data.titleUz,
        unit: data.unit,
        unitValue: data.unitValue,
      });
    }
  }, [data]);

  const { mutate: CreateReference } = useMutation({
    mutationFn: async (payload) => {
      return await axiosInstance.post('/cargo-reference-book', payload);
    },
    onSuccess: () => {
      setAlert({ type: 'success', message: "Narx qo'shildi" });
      queryClient.invalidateQueries({ queryKey: ['reference_list'] });
      resetForm();
    },
    onError: () => {
      setAlert({ type: 'warning', message: "Narx qo'shishida xatolik yuz berdi" });
    },
  });

  const { mutate: updateWarhouses } = useMutation({
    mutationFn: async (payload) => {
      return await axiosInstance.put(`/cargo-reference-book/${idHouses}`, payload);
    },
    onSuccess: () => {
      setAlert({ type: 'success', message: 'Narx yangilandi' });
      queryClient.invalidateQueries({ queryKey: ['reference_list'] });
      setIdHouses(null);
      resetForm();
    },
    onError: () => {
      setAlert({ type: 'warning', message: "Narx qo'yangilanshda xatolik yuz berdi" });
    },
  });

  const handleAdd = (e) => {
    e.preventDefault();
    const isFormValid = formData.titleUz.trim() !== '' && formData.titleRu.trim() !== '' && formData.shortDescriptionUz.trim() !== '' && formData.shortDescriptionRu.trim() !== '' && formData.unit.trim() !== '' && formData.cargoType.trim() !== '' && formData.price > 0 && formData.unitValue > 0;

    if (!isFormValid) {
      setAlert({ type: 'warning', message: "Iltimos barcha maydonlarni to'ldiring!" });
      return;
    } else {
      CreateReference({
        titleUz: formData.titleUz,
        titleRu: formData.titleRu,
        shortDescriptionUz: formData.shortDescriptionUz,
        shortDescriptionRu: formData.shortDescriptionRu,
        price: formData.price,
        exchange: formData.exchange,
        unit: formData.unit,
        unitValue: formData.unitValue,
        cargoType: formData.cargoType,
      });
    }
  };

  const handleUpdate = (e) => {
    e.preventDefault();
    const isFormValid = formData.titleUz.trim() !== '' && formData.titleRu.trim() !== '' && formData.shortDescriptionUz.trim() !== '' && formData.shortDescriptionRu.trim() !== '' && formData.unit.trim() !== '' && formData.cargoType.trim() !== '' && formData.price > 0 && formData.unitValue > 0;

    if (!isFormValid) {
      setAlert({ type: 'warning', message: "Iltimos barcha maydonlarni to'ldiring!" });
      return;
    } else {
      updateWarhouses({
        titleUz: formData.titleUz,
        titleRu: formData.titleRu,
        shortDescriptionUz: formData.shortDescriptionUz,
        shortDescriptionRu: formData.shortDescriptionRu,
        price: formData.price,
        exchange: formData.exchange,
        unit: formData.unit,
        unitValue: formData.unitValue,
        cargoType: formData.cargoType,
      });
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  return (
    <div className="flex flex-col bg-white shadow rounded-lg p-6 mb-6">
      <form className="space-y-6" onSubmit={idHouses !== null ? handleUpdate : handleAdd}>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">Nomi (Uz)</label>
            <input type="text" name="titleUz" value={formData.titleUz} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required autoComplete="off" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Nomi (Ru)</label>
            <input type="text" name="titleRu" value={formData.titleRu} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required autoComplete="off" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Qisqacha tarif (UZ)</label>
            <input type="text" name="shortDescriptionUz" value={formData.shortDescriptionUz} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required autoComplete="off" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Qisqacha tarif (RU)</label>
            <input type="text" name="shortDescriptionRu" value={formData.shortDescriptionRu} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required autoComplete="off" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Valyuta</label>
            <input type="text" name="exchange" disabled value={formData.exchange} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required autoComplete="off" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">O'lchov birligi</label>
            <input type="text" name="unit" value={formData.unit} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Qiymati</label>
            <input type="text" name="unitValue" value={formData.unitValue} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Narxi</label>
            <input type="text" name="price" value={formData.price} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Cargo Type</label>
            <select name="cargoType" value={formData.cargoType} onChange={handleChange} className="w-full border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3489e3]" required>
              <option value="AVIA">AVIA</option>
              <option value="AUTO">AUTO</option>
            </select>
          </div>
        </div>
        <div className="flex flex-wrap gap-3 mb-8 mt-6">
          {idHouses === null && <button className="bg-[#3489e3] hover:bg-blue-500 text-white px-5 py-2 rounded-lg shadow">Qo'shish</button>}
          {idHouses !== null && <button className={`px-5 py-2 rounded-lg shadow text-white  bg-[#3489e3] hover:bg-blue-500`}>Yangilash</button>}
          <button
            onClick={() => {
              setFormData({ auto: '', avia: '' }), setIdHouses(null);
            }}
            className="bg-gray-400 hover:bg-gray-500 text-white px-5 py-2 rounded-lg shadow"
          >
            Tozalash
          </button>
        </div>
      </form>
    </div>
  );
};

export default CreateReference;
