'use client'

import React, { useCallback, useEffect, useState } from 'react'
import * as yup from 'yup'
import { Controller, useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import {
  Badge,
  Button,
  Card,
  Checkbox,
  HelperText,
  Label,
  Select,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'
import { DateType } from 'react-tailwindcss-datepicker'
import { useRouter } from 'next/navigation'
import { toast } from 'react-toastify'

import {
  FastboatName,
  FastboatProduct,
  FastboatRoute,
} from '@/lib/types/product/fastboat'
import { paginationDefaultData } from '@/lib/data/pagination'
import {
  getFastboatNames,
  getFastboatProducts,
  getFastboatRoutes,
} from '@/lib/services/fastboat-services'
import { useMerchant } from '@/lib/context/MerchantContext'
import { handleApiError } from '@/lib/utils/error-handler'
import * as PaginationConstant from '@/lib/constants/pagination'
import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import { getKualaLumpurDate } from '@/lib/utils/date'
import formTheme from '@/lib/themes/form'
import tableTheme from '@/lib/themes/table'
import { capitalizeWords } from '@/lib/utils/string'
import buttonTheme from '@/lib/themes/button'
import Pagination from '@/lib/components/Pagination'
import { createFastboatDisabledOperation } from '@/lib/services/fastboat-disabled-operations'
import PageHeader from '@/lib/components/PageHeader'
import { FastboatDisabledOperationPayload } from '../types'
import { useAuth } from '@/lib/context/AuthContext'

const formSchema = yup.object({
  fastboat_product_ids: yup
    .array()
    .of(yup.number().required())
    .min(1, 'At least one fastboat product must be selected')
    .required('Fastboat products are required'),
  start_date: yup.string().required('Disabled date range is required'),
  end_date: yup.string().required('Disabled date range is required'),
})

export default function MainContent() {
  const router = useRouter()
  const { merchant } = useMerchant()
  const { user, userManagedMerchants } = useAuth()

  const [fastboatNames, setFastboatNames] = useState<FastboatName[]>([])
  const [fastboatRoutes, setFastboatRoutes] = useState<FastboatRoute[]>([])
  const [fastboatProducts, setFastboatProducts] = useState<
    Pagination<FastboatProduct>
  >(paginationDefaultData)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [searchForm, setSearchForm] = useState<{
    searching: boolean
    params: {
      fastboatNameId: number | null
      fastboatRouteId: number | null
      page: number
      limit: number
    }
  }>({
    searching: false,
    params: {
      fastboatNameId: null,
      fastboatRouteId: null,
      page: 1,
      limit: PaginationConstant.MIN_DATA_PER_PAGE,
    },
  })

  const [processing, setProcessing] = useState(false)
  const {
    handleSubmit,
    watch,
    setValue,
    trigger,
    setError,
    control,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      fastboat_product_ids: [],
      start_date: getKualaLumpurDate().toISOString().split('T')[0],
      end_date: getKualaLumpurDate().toISOString().split('T')[0],
    },
  })

  const formValues = watch()

  const fetchFastboatProducts = useCallback(async () => {
    setSearchForm((prev) => ({
      ...prev,
      searching: true,
    }))

    try {
      const fastboatProducts = await getFastboatProducts({
        merchantId: merchant?.id as number,
        page: searchForm.params.page,
        limit: searchForm.params.limit,
        fastboatNameId: searchForm.params.fastboatNameId || undefined,
        routeId: searchForm.params.fastboatRouteId || undefined,
      })

      setFastboatProducts(fastboatProducts)
    } catch (error) {
      handleApiError(
        error,
        'Something went wrong while fetching fastboat products.',
      )
    } finally {
      setSearchForm((prev) => ({
        ...prev,
        searching: false,
      }))
    }
  }, [merchant, searchForm.params])

  useEffect(() => {
    if (!merchant) return

    const fetchFastboatNames = async () => {
      try {
        const fastboatNames = await getFastboatNames(merchant?.id as number)
        setFastboatNames(fastboatNames)
      } catch (error) {
        handleApiError(
          error,
          'Something went wrong while fetching fastboat names.',
        )
      }
    }

    const fetchFastboatRoutes = async () => {
      try {
        const fastboatRoutes = await getFastboatRoutes(merchant?.id as number)
        setFastboatRoutes(fastboatRoutes)
      } catch (error) {
        handleApiError(
          error,
          'Something went wrong while fetching fastboat routes.',
        )
      }
    }

    Promise.allSettled([
      fetchFastboatNames(),
      fetchFastboatRoutes(),
      fetchFastboatProducts(),
    ])
  }, [merchant, fetchFastboatProducts])

  function toggleCheckAllProducts() {
    const allProductIds = fastboatProducts.data.map((product) => product.id)
    const checkedProductIds = formValues.fastboat_product_ids || []

    const allChecked = allProductIds.length === checkedProductIds.length

    setValue('fastboat_product_ids', [...(allChecked ? [] : allProductIds)])
    trigger('fastboat_product_ids')
  }

  function toggleCheckProduct(fastboatProductId: number) {
    const checkedProductIds = formValues.fastboat_product_ids || []

    const isAlreadyChecked = checkedProductIds.includes(fastboatProductId)

    let updatedCheckedProductIds: number[] = []

    if (isAlreadyChecked) {
      updatedCheckedProductIds = checkedProductIds.filter(
        (id) => id !== fastboatProductId,
      )
    } else {
      updatedCheckedProductIds = [...checkedProductIds, fastboatProductId]
    }

    setValue('fastboat_product_ids', updatedCheckedProductIds)
    trigger('fastboat_product_ids')
  }

  async function onSubmit(data: FastboatDisabledOperationPayload) {
    try {
      setProcessing(true)

      await createFastboatDisabledOperation({
        merchantId: merchant?.id as number,
        payload: data,
      })

      toast.success('Fastboat disabled operation created successfully!')

      router.push(
        `/merchant-dashboard/${merchant?.id}/fastboat-disabled-operations`,
      )
    } catch (error) {
      handleApiError(error, 'An unexpected error occurred.', (formErrors) => {
        Object.keys(formErrors).forEach((field) => {
          setError(field as keyof FastboatDisabledOperationPayload, {
            type: 'server',
            message: formErrors[field][0],
          })
        })
      })
    } finally {
      setProcessing(false)
    }
  }

  async function handlePageChange(page: number) {
    setRefreshTrigger((prev) => prev + 1)

    setSearchForm((prev) => ({
      ...prev,
      searching: true,
      params: {
        ...prev.params,
        page,
      },
    }))
  }

  function handleLimitChange(limit: number) {
    setRefreshTrigger((prev) => prev + 1)

    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        page: 1,
        limit,
      },
    }))
  }

  function handleChangeFastboatName(fastboatNameId: number | null) {
    setRefreshTrigger((prev) => prev + 1)

    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        fastboatNameId,
        page: 1,
      },
    }))
  }

  function handleChangeFastboatRoute(fastboatRouteId: number | null) {
    setRefreshTrigger((prev) => prev + 1)

    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        fastboatRouteId,
        page: 1,
      },
    }))
  }

  useEffect(() => {
    if (!merchant) return

    const timeoutId = setTimeout(() => {
      fetchFastboatProducts()
    }, 500)

    return () => clearTimeout(timeoutId)
  }, [merchant, refreshTrigger, fetchFastboatProducts])

  // Authorize User
  useEffect(() => {
    // Make sure all necessary data is loaded before authorization check
    if (!user || !merchant || userManagedMerchants.length === 0) return

    if (
      user.role === 'accounting' ||
      user.role === 'supervisor' ||
      !userManagedMerchants.includes(merchant.id as number)
    ) {
      return router.replace(`/merchant-dashboard/${merchant.id}`)
    }
  }, [user, merchant, userManagedMerchants, router])

  return (
    <Card className="max-w-5xl mt-6 shadow-none mx-auto">
      <PageHeader
        title="Disable Boat Operations"
        description="Select boat schedule that you want to disabled."
      />

      <form
        className="flex w-full flex-col gap-4 mt-10"
        onSubmit={handleSubmit(onSubmit)}
      >
        {/* Disabled Date Range */}
        <div className="w-full">
          <div className="mb-2 block">
            <Label htmlFor="disabled_date_range">Disabled Date Range</Label>
          </div>

          <Controller
            name="start_date"
            control={control}
            render={({ field }) => (
              <DatePicker
                inputId="disabled_date_range"
                minDate={new Date()}
                value={{
                  startDate: field.value as unknown as DateType,
                  endDate: formValues.end_date as unknown as DateType,
                }}
                onDateChange={(formattedDate: FormattedDate) => {
                  field.onChange(formattedDate.startDate)
                  setValue('end_date', formattedDate.endDate as string)
                }}
              />
            )}
          />
          {(errors.start_date || errors.end_date) && (
            <HelperText color="failure">
              {errors.start_date?.message || errors.end_date?.message}
            </HelperText>
          )}
        </div>

        {/* Boat Schedules */}
        <section className="mt-6">
          <h4 className="font-semibold text-2xl">Boat Schedules</h4>

          {/* Search Form */}
          <div className="grid grid-cols-1 sm:grid-cols-2 w-full gap-4 mt-2">
            {/* Boat Name */}
            <div className="w-full">
              <div className="block mb-2">
                <Label htmlFor="fastboat_name_id" theme={formTheme.label}>
                  Boat Name
                </Label>
              </div>

              <Select
                id="fastboat_name_id"
                theme={formTheme.select}
                value={searchForm.params.fastboatNameId || ''}
                className="w-full"
                onChange={(e) => {
                  handleChangeFastboatName(
                    e.target.value ? +e.target.value : null,
                  )
                }}
              >
                <option value="">All</option>
                {fastboatNames.map((name) => (
                  <option key={name.id} value={name.id}>
                    {name.name}
                  </option>
                ))}
              </Select>
            </div>

            {/* Port Route */}
            <div className="w-full">
              <div className="mb-2 block">
                <Label theme={formTheme.label} htmlFor="fastboat_route_id">
                  Port Route
                </Label>
              </div>
              <Select
                id="fastboat_route_id"
                theme={formTheme.select}
                value={searchForm.params?.fastboatRouteId || ''}
                onChange={(e) => {
                  handleChangeFastboatRoute(
                    e.target.value ? +e.target.value : null,
                  )
                }}
              >
                <option value="">All</option>
                {fastboatRoutes?.map((route) => (
                  <option key={route.id} value={route.id}>
                    {route.departure_harbor} &#8596; {route.arrival_harbor}
                  </option>
                ))}
              </Select>
            </div>
          </div>
          {/* End of Search Form */}

          <div className="mt-6 relative overflow-auto">
            <Table theme={tableTheme.table}>
              <TableHead>
                <TableHeadCell className="p-4 text-center">
                  <Checkbox
                    color="blue"
                    onChange={toggleCheckAllProducts}
                    checked={
                      fastboatProducts.data.length > 0 &&
                      formValues.fastboat_product_ids?.length ===
                        fastboatProducts.data.length
                    }
                  />
                </TableHeadCell>
                <TableHeadCell className="text-nowrap p-4">
                  Boat Name
                </TableHeadCell>
                <TableHeadCell className="text-nowrap p-4">
                  Port Route
                </TableHeadCell>
                <TableHeadCell className="text-nowrap p-4">
                  Time Schedule
                </TableHeadCell>
              </TableHead>

              <TableBody>
                {fastboatProducts.data?.length === 0 &&
                !searchForm.searching ? (
                  <TableRow>
                    <TableCell className="p-4 text-center" colSpan={4}>
                      No fastboat products found.
                    </TableCell>
                  </TableRow>
                ) : searchForm.searching ? (
                  Array.from({ length: 6 }).map((_, idx) => (
                    <TableRow
                      key={`sk-${idx}`}
                      className="bg-white animate-pulse"
                    >
                      <TableCell className="p-4 text-center">
                        <div className="w-4 h-4 bg-slate-200 rounded mx-auto" />
                      </TableCell>

                      {Array.from({ length: 3 }).map((_, cellIdx) => (
                        <TableCell key={cellIdx} className="text-center p-4">
                          <div className="w-full h-4 rounded bg-slate-200 mx-auto" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : (
                  <React.Fragment>
                    {fastboatProducts.data?.map((fastboatProduct) => (
                      <TableRow key={fastboatProduct.id}>
                        <TableCell className="p-4 text-center">
                          <Checkbox
                            color="blue"
                            checked={formValues.fastboat_product_ids?.includes(
                              fastboatProduct.id,
                            )}
                            onChange={() => {
                              toggleCheckProduct(fastboatProduct.id)
                            }}
                          />
                        </TableCell>

                        {/* Boat Name */}
                        <TableCell className="text-nowrap p-4">
                          {fastboatProduct.boat_name}
                        </TableCell>

                        {/* Port Route */}
                        <TableCell className="text-nowrap flex items-center gap-2 p-4">
                          {fastboatProduct.route.departure_harbor} to{' '}
                          {fastboatProduct.route.arrival_harbor}
                          <Badge
                            color={
                              fastboatProduct.route.type === 'direct'
                                ? 'blue'
                                : 'amber'
                            }
                          >
                            {capitalizeWords(fastboatProduct.route.type)}
                          </Badge>
                        </TableCell>

                        {/* Time Schedule */}
                        <TableCell className="text-nowrap p-4">
                          {fastboatProduct.departure_time} to{' '}
                          {fastboatProduct.arrival_time}
                        </TableCell>
                      </TableRow>
                    ))}
                  </React.Fragment>
                )}
              </TableBody>
            </Table>
          </div>

          {!searchForm.searching && (
            <Pagination
              currentPage={fastboatProducts.current_page}
              lastPage={fastboatProducts.last_page}
              limit={searchForm.params.limit}
              from={fastboatProducts.from}
              to={fastboatProducts.to}
              total={fastboatProducts.total}
              handlePageChange={handlePageChange}
              handleLimitChange={handleLimitChange}
            />
          )}
        </section>

        <div className="flex gap-2 mt-6 justify-end">
          <Button
            type="button"
            color="light"
            className="w-52"
            theme={buttonTheme.button}
            disabled={processing}
            onClick={() => {
              router.replace(
                `/merchant-dashboard/${merchant?.id}/fastboat-disabled-operations`,
              )
            }}
          >
            Cancel
          </Button>
          <Button
            type="submit"
            color="blue"
            className="w-52"
            disabled={processing}
            theme={buttonTheme.button}
          >
            Create
          </Button>
        </div>
      </form>
    </Card>
  )
}
