import { type FC, useState } from 'react'
import { Add, Image } from 'iconsax-react'
import Input from '@/components/Input'
import SwitchComponent from '@/components/Switch'
import Button from '@/components/Button'
import type { FormikProps } from 'formik'
import { useGetCategories, useGetIcons } from '../hooks/useProductData'
import IconSelectModal from './IconSelectModal'
import Select from '@/components/Select'

type CategoryFormValues = {
  title: string
  icon: File[]
  order: number,
  parentId?: string,
}

type Props = {
  formik: FormikProps<CategoryFormValues>
  isActive: boolean
  onActiveChange: (value: boolean) => void
  onIconChange?: (files: File[]) => void
  iconFiles?: File[]
  isSubmitting: boolean
  isEditing?: boolean
  onIconUrlChange?: (url: string) => void
  selectedIconUrl?: string
}

const CategoryForm: FC<Props> = ({
  formik,
  isActive,
  onActiveChange,
  isSubmitting,
  isEditing = false,
  onIconUrlChange,
  selectedIconUrl
}) => {

  const { data: iconsData } = useGetIcons()
  const { data: categories } = useGetCategories()
  const icons = iconsData?.data || []
  const [isIconModalOpen, setIsIconModalOpen] = useState(false)

  const handleIconSelect = (url: string) => {
    if (onIconUrlChange) {
      onIconUrlChange(url)
    }
    setIsIconModalOpen(false)
  }

  return (
    <div className="w-full lg:w-[300px] bg-white rounded-3xl p-4 lg:p-6 h-fit lg:sticky top-4 lg:top-6">
      <h2 className="font-light mb-4 lg:mb-6 text-sm lg:text-base">{isEditing ? 'ویرایش دسته بندی' : 'اضافه کردن دسته بندی'}</h2>

      <div className="flex items-center justify-between mb-4 lg:mb-6">
        <div className="text-xs lg:text-sm">فعال</div>
        <SwitchComponent
          active={isActive}
          onChange={onActiveChange}
        />
      </div>

      <div className="mb-3 lg:mb-4">
        <Input
          label="عنوان دسته بندی"
          name="title"
          value={formik.values.title}
          onChange={formik.handleChange}
          error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
        />
      </div>

      <div className='mb-3 lg:mb-4'>
        <Select
          label='والد (اختیاری)'
          items={
            categories?.data
              ?.filter((item) => !item.parent)
              ?.map((item) => ({ label: item.title, value: item.id })) ?? []
          }
          placeholder='انتخاب'
          {...formik.getFieldProps('parentId')}
        />
      </div>

      <div className="mb-3 lg:mb-4">
        <Input
          label="اولویت"
          name="order"
          type="number"
          value={formik.values.order}
          onChange={(e) => formik.setFieldValue('order', Number(e.target.value))}
          error_text={formik.touched.order && formik.errors.order ? formik.errors.order : ''}
        />
      </div>

      <div className="mb-4 lg:mb-6">
        <div className="text-xs lg:text-sm mb-2 font-medium">آیکون دسته بندی</div>
        <Button
          type="button"
          onClick={() => setIsIconModalOpen(true)}
          className="w-full max-h-10 lg:h-12 flex items-center justify-center gap-2 text-xs lg:text-sm"
        >
          <Image size={18} color="#fff" className="lg:w-5 lg:h-5" />
          <span>انتخاب آیکون</span>
        </Button>
        {selectedIconUrl && (
          <div className="mt-3 flex items-center gap-2 lg:gap-3 p-2 lg:p-3 bg-gray-50 rounded-xl border border-gray-200">
            <div className="w-10 h-10 lg:w-12 lg:h-12 flex items-center justify-center bg-white rounded-lg border border-gray-200 p-1.5 lg:p-2 flex-shrink-0">
              <img
                src={selectedIconUrl}
                alt="selected icon"
                className="w-full h-full object-contain max-w-full max-h-full"
                style={{
                  imageRendering: 'auto',
                  objectFit: 'contain'
                }}
                onError={(e) => {
                  e.currentTarget.style.display = 'none'
                }}
              />
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[10px] lg:text-xs text-gray-500 mb-0.5 lg:mb-1">آیکون انتخاب شده</div>
              <div className="text-[10px] lg:text-xs text-gray-400 truncate">
                {selectedIconUrl}
              </div>
            </div>
            <button
              type="button"
              onClick={() => {
                if (onIconUrlChange) {
                  onIconUrlChange('')
                }
              }}
              className="text-gray-400 hover:text-red-500 transition-colors text-lg lg:text-xl leading-none flex-shrink-0 w-5 h-5 lg:w-6 lg:h-6 flex items-center justify-center"
              title="حذف آیکون"
            >
              ×
            </button>
          </div>
        )}
      </div>

      <IconSelectModal
        open={isIconModalOpen}
        onClose={() => setIsIconModalOpen(false)}
        icons={icons}
        onSelect={handleIconSelect}
        selectedUrl={selectedIconUrl}
      />

      <Button
        onClick={() => formik.handleSubmit()}
        className="w-full min-h-10 lg:h-auto text-xs lg:text-sm"
        isloading={isSubmitting}
      >
        <Add color='#fff' size={18} className="ml-2 lg:w-5 lg:h-5" />
        ذخیره
      </Button>
    </div>
  )
}

export default CategoryForm
