"use client";
import { useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { addBranch, editBranch } from "@/Services/Branches/ApiBranches";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import CustomInput from "@/components/ui/FormInput/CustomInput";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const schema = yup.object({
  location_type: yup.string().required("Location type is required"),
  name: yup.string(),
  address: yup.string(),
  city: yup.string(),
  state: yup.string(),
  pincode: yup.string(),
  phone: yup.string(),
  is_active: yup.boolean().default(true),
});

export default function AddBranchForm({
  type = "add",
  editData = null,
  onClose,
}) {
  const queryClient = useQueryClient();

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      location_type: "branch",
      name: "",
      address: "",
      city: "",
      state: "",
      pincode: "",
      phone: "",
      is_active: true,
    },
  });

  useEffect(() => {
    if (editData) {
      reset({
        location_type: editData.location_type,
        name: editData.name || "",
        address: editData.address,
        city: editData.city,
        state: editData.state || "",
        pincode: editData.pincode || "",
        phone: editData.phone || "",
        is_active: editData.is_active === 1,
      });
    } else {
      reset({
        location_type: "branch",
        name: "",
        address: "",
        city: "",
        state: "",
        pincode: "",
        phone: "",
        is_active: true,
      });
    }
  }, [editData, reset]);

  const addMutation = useMutation({
    mutationFn: addBranch,
    onSuccess: () => {
      queryClient.invalidateQueries(["branches"]);
      reset();
      onClose();
    },
  });

  const editMutation = useMutation({
    mutationFn: editBranch,
    onSuccess: () => {
      queryClient.invalidateQueries(["branches"]);
      reset();
      onClose();
    },
  });

  const onSubmit = (data) => {
    const payload = {
      ...data,
      is_active: data.is_active ? 1 : 0,
    };

    if (editData?.id) {
      payload.id = editData.id;
      editMutation.mutate(payload);
    } else {
      addMutation.mutate(payload);
    }
  };

  return (
    <div className="bg-white pt-0 w-full border border-gray-200 rounded-md">
      <div className="flex justify-between items-center border-b p-4 bg-brand-dark/5">
        <h2 className="text-xl font-semibold text-brand-dark">
          {type === "add" ? "Add" : "Edit"} Branch
        </h2>

        <Controller
          control={control}
          name="is_active"
          render={({ field }) => (
            <div className="flex items-center space-x-2">
              <label className="text-sm">Active</label>
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            </div>
          )}
        />
      </div>
      <form onSubmit={handleSubmit(onSubmit)} className="p-6 space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Controller
            name="location_type"
            control={control}
            render={({ field }) => (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Location Type <span className="text-red-500">*</span>
                </label>

                <Select
                  key={field.value}
                  value={field.value}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select location type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="branch">Branch</SelectItem>
                    <SelectItem value="franchise">Franchise</SelectItem>
                    <SelectItem value="associated">Associated</SelectItem>
                  </SelectContent>
                </Select>

                {errors.location_type && (
                  <p className="text-red-500 text-sm mt-1">
                    {errors.location_type.message}
                  </p>
                )}
              </div>
            )}
          />

          <Controller
            name="name"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Branch Name (Optional)"
                placeholder="e.g., Main Branch"
                errors={errors}
              />
            )}
          />

          <Controller
            name="address"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Address"
                placeholder="Street address"
                errors={errors}
                required
              />
            )}
          />

          <Controller
            name="city"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="City"
                placeholder="City name"
                errors={errors}
                required
              />
            )}
          />

          <Controller
            name="state"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="State (Optional)"
                placeholder="State name"
                errors={errors}
              />
            )}
          />

          <Controller
            name="pincode"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Pincode (Optional)"
                placeholder="e.g., 600001"
                errors={errors}
              />
            )}
          />

          <Controller
            name="phone"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Phone (Optional)"
                placeholder="e.g., +91 1234567890"
                errors={errors}
              />
            )}
          />
        </div>
        <div className="flex justify-end">
          <Button variant="dark" type="submit">
            {editData ? "Update" : "Add"} Branch
          </Button>
        </div>
      </form>
    </div>
  );
}
