import {
  mdiCalendarCheck,
  mdiChartTimelineVariant,
  mdiClipboardTextClock,
  mdiFish,
  mdiFoodDrumstick,
  mdiStorefront,
  mdiWaterPercent,
} from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useMemo, useState } from 'react'
import axios from 'axios'
import BaseButton from '../components/BaseButton'
import CardBox from '../components/CardBox'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import BaseIcon from '../components/BaseIcon'
import { getPageTitle } from '../config'
import { hasPermission } from '../helpers/userPermissions'
import { useAppSelector } from '../stores/hooks'
import { useTranslation } from 'react-i18next'
import { translateCrudLabel } from '../helpers/translateCrudLabel'

type Option = {
  id: string
  label: string
}

type FeedLog = {
  id: string
  fed_at?: string
  quantity_kg?: string | number
  feeding_method?: string
  appetite?: string
  notes?: string
  batch?: { id?: string; batch_code?: string }
  feed_product?: { id?: string; product_name?: string }
  recorded_by?: { firstName?: string; lastName?: string; email?: string }
  createdAt?: string
}

type OpsForm = {
  batch: string
  feed_product: string
  fed_at: string
  quantity_kg: string
  feeding_method: string
  appetite: string
  notes: string
}

const initialForm: OpsForm = {
  batch: '',
  feed_product: '',
  fed_at: '',
  quantity_kg: '',
  feeding_method: 'manual',
  appetite: 'normal',
  notes: '',
}

const nowForDateTimeLocal = () => {
  const date = new Date()
  date.setMinutes(date.getMinutes() - date.getTimezoneOffset())
  return date.toISOString().slice(0, 16)
}

const formatDateTime = (value?: string, locale = 'id', emptyLabel = 'Not scheduled') => {
  if (!value) return emptyLabel

  return new Intl.DateTimeFormat(locale, {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(new Date(value))
}

const formatQuantity = (value?: string | number, locale = 'id') => {
  if (value === undefined || value === null || value === '') return '0 kg'

  return `${Number(value).toLocaleString(locale, { maximumFractionDigits: 2 })} kg`
}

const getRecorder = (log?: FeedLog, fallback = 'Team member') => {
  const firstName = log?.recorded_by?.firstName || ''
  const lastName = log?.recorded_by?.lastName || ''
  const fullName = `${firstName} ${lastName}`.trim()

  return fullName || log?.recorded_by?.email || fallback
}

const statusStyles = {
  low: 'bg-amber-100 text-amber-800 ring-amber-200',
  normal: 'bg-emerald-100 text-emerald-800 ring-emerald-200',
  high: 'bg-sky-100 text-sky-800 ring-sky-200',
}

const FarmOpsPage = () => {
  const { t, i18n } = useTranslation('common')
  const locale = i18n.resolvedLanguage || i18n.language || 'id'
  const tr = (value: string) => translateCrudLabel(value, t)
  const { currentUser } = useAppSelector((state) => state.auth)
  const [logs, setLogs] = useState<FeedLog[]>([])
  const [batchOptions, setBatchOptions] = useState<Option[]>([])
  const [feedOptions, setFeedOptions] = useState<Option[]>([])
  const [selectedLog, setSelectedLog] = useState<FeedLog | null>(null)
  const [form, setForm] = useState<OpsForm>({ ...initialForm, fed_at: nowForDateTimeLocal() })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  const canCreateFeedLog = currentUser && hasPermission(currentUser, 'CREATE_FEEDING_LOGS')

  const totalFedToday = useMemo(() => {
    const today = new Date().toDateString()

    return logs
      .filter((log) => log.fed_at && new Date(log.fed_at).toDateString() === today)
      .reduce((sum, log) => sum + Number(log.quantity_kg || 0), 0)
  }, [logs])

  const activeBatchCount = useMemo(() => {
    const ids = new Set(logs.map((log) => log.batch?.id).filter(Boolean))

    return ids.size
  }, [logs])

  const latestAppetite = tr(logs[0]?.appetite || 'normal')

  const fetchWorkspace = async () => {
    setLoading(true)
    setError('')

    try {
      const [feedLogResponse, batchResponse, feedProductResponse] = await Promise.all([
        axios.get('/feeding_logs?limit=12&field=fed_at&sort=DESC'),
        axios.get('/batches/autocomplete?limit=100'),
        axios.get('/feed_products/autocomplete?limit=100'),
      ])

      const latestLogs = Array.isArray(feedLogResponse.data?.rows) ? feedLogResponse.data.rows : []
      const batches = Array.isArray(batchResponse.data) ? batchResponse.data : []
      const feeds = Array.isArray(feedProductResponse.data) ? feedProductResponse.data : []

      setLogs(latestLogs)
      setBatchOptions(batches)
      setFeedOptions(feeds)
      setSelectedLog((current) => current || latestLogs[0] || null)
      setForm((current) => ({
        ...current,
        batch: current.batch || batches[0]?.id || '',
        feed_product: current.feed_product || feeds[0]?.id || '',
      }))
    } catch (fetchError) {
      console.error('Farm ops workspace failed to load', fetchError)
      setError(tr('Could not load the farm operations workspace. Please refresh or check your permissions.'))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchWorkspace()
  }, [])

  const handleChange = (field: keyof OpsForm, value: string) => {
    setForm((current) => ({ ...current, [field]: value }))
  }

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setError('')
    setMessage('')

    if (!form.batch) {
      setError(tr('Choose a batch before recording feed.'))
      return
    }

    if (!form.fed_at) {
      setError(tr('Add the feeding time.'))
      return
    }

    if (!form.quantity_kg || Number(form.quantity_kg) <= 0) {
      setError(tr('Feed quantity must be greater than 0 kg.'))
      return
    }

    setSaving(true)

    try {
      await axios.post('/feeding_logs', {
        data: {
          batch: form.batch,
          feed_product: form.feed_product || null,
          fed_at: new Date(form.fed_at).toISOString(),
          quantity_kg: form.quantity_kg,
          feeding_method: form.feeding_method,
          appetite: form.appetite,
          notes: form.notes,
          recorded_by: currentUser?.id || null,
        },
      })

      setMessage(tr('Feeding record saved. The latest activity list has been refreshed.'))
      setForm({ ...initialForm, fed_at: nowForDateTimeLocal(), batch: form.batch, feed_product: form.feed_product })
      await fetchWorkspace()
    } catch (saveError) {
      console.error('Farm ops feeding log save failed', saveError)
      setError(tr('Could not save the feeding record. Please check the values and try again.'))
    } finally {
      setSaving(false)
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(tr('Farm Ops Command Center'))}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Farm Ops Command Center" main>
          <BaseButton href="/feeding_logs/feeding_logs-list" label="Open full CRUD" color="whiteDark" />
        </SectionTitleLineWithButton>

        <section className="mb-6 overflow-hidden rounded-3xl bg-gradient-to-br from-[#042f2e] via-[#075985] to-[#0f766e] p-1 shadow-xl">
          <div className="rounded-[1.35rem] bg-white/10 p-6 text-white backdrop-blur md:p-8">
            <div className="grid gap-6 lg:grid-cols-[1.35fr_0.65fr] lg:items-end">
              <div>
                <p className="mb-3 inline-flex rounded-full bg-white/15 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-cyan-100 ring-1 ring-white/20">
                  {tr('Multi-tenant aquaculture workflow')}
                </p>
                <h2 className="max-w-3xl text-3xl font-black tracking-tight md:text-5xl">
                  {tr('Record feed, monitor appetite, and keep the farm team aligned.')}
                </h2>
                <p className="mt-4 max-w-2xl text-sm leading-6 text-cyan-50 md:text-base">
                  {tr('A focused daily operations slice built on top of your generated CRUD entities: batches, feed products, and feeding logs.')}
                </p>
              </div>
              <div className="grid grid-cols-3 gap-3 text-center">
                <div className="rounded-2xl bg-white/15 p-4 ring-1 ring-white/20">
                  <div className="text-2xl font-black">{formatQuantity(totalFedToday, locale)}</div>
                  <div className="mt-1 text-xs text-cyan-100">{tr('Fed today')}</div>
                </div>
                <div className="rounded-2xl bg-white/15 p-4 ring-1 ring-white/20">
                  <div className="text-2xl font-black">{activeBatchCount}</div>
                  <div className="mt-1 text-xs text-cyan-100">{tr('Active batches')}</div>
                </div>
                <div className="rounded-2xl bg-white/15 p-4 ring-1 ring-white/20">
                  <div className="text-2xl font-black capitalize">{latestAppetite}</div>
                  <div className="mt-1 text-xs text-cyan-100">{tr('Latest appetite')}</div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {(message || error) && (
          <div
            className={`mb-6 rounded-2xl px-4 py-3 text-sm ring-1 ${
              error ? 'bg-rose-50 text-rose-800 ring-rose-200' : 'bg-emerald-50 text-emerald-800 ring-emerald-200'
            }`}
          >
            {error || message}
          </div>
        )}

        <div className="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
          <CardBox className="border-0 shadow-lg ring-1 ring-slate-200/80 dark:ring-dark-700">
            <div className="mb-5 flex items-start justify-between gap-4">
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-teal-600">{tr('Quick input')}</p>
                <h3 className="mt-1 text-2xl font-bold text-slate-900 dark:text-white">{tr('Log a feeding')}</h3>
                <p className="mt-1 text-sm text-slate-500">{tr('Capture the minimum operational data and confirm it immediately.')}</p>
              </div>
              <span className="rounded-2xl bg-teal-50 p-3 text-teal-700 ring-1 ring-teal-100">
                <BaseIcon path={mdiFoodDrumstick} size="24" />
              </span>
            </div>

            {loading ? (
              <div className="rounded-2xl bg-slate-50 p-6 text-sm text-slate-500">{tr('Loading batches and feed products')}</div>
            ) : batchOptions.length === 0 ? (
              <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-sm text-slate-600">
                <p className="font-semibold text-slate-900">{tr('No batches available yet')}</p>
                <p className="mt-2">{tr('Create a batch first, then return here to record daily feeding activity')}</p>
                <BaseButton href="/batches/batches-new" label="Create batch" color="info" className="mt-4" />
              </div>
            ) : (
              <form className="space-y-4" onSubmit={handleSubmit}>
                <label className="block">
                  <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Batch')}</span>
                  <select
                    className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                    value={form.batch}
                    onChange={(event) => handleChange('batch', event.target.value)}
                    disabled={!canCreateFeedLog || saving}
                  >
                    {batchOptions.map((batch) => (
                      <option key={batch.id} value={batch.id}>
                        {batch.label}
                      </option>
                    ))}
                  </select>
                </label>

                <div className="grid gap-4 md:grid-cols-2">
                  <label className="block">
                    <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Fed at')}</span>
                    <input
                      className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                      type="datetime-local"
                      value={form.fed_at}
                      onChange={(event) => handleChange('fed_at', event.target.value)}
                      disabled={!canCreateFeedLog || saving}
                    />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('QuantityKg')}</span>
                    <input
                      className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                      min="0"
                      step="0.01"
                      type="number"
                      value={form.quantity_kg}
                      onChange={(event) => handleChange('quantity_kg', event.target.value)}
                      disabled={!canCreateFeedLog || saving}
                    />
                  </label>
                </div>

                <div className="grid gap-4 md:grid-cols-3">
                  <label className="block md:col-span-1">
                    <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Feed product')}</span>
                    <select
                      className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                      value={form.feed_product}
                      onChange={(event) => handleChange('feed_product', event.target.value)}
                      disabled={!canCreateFeedLog || saving}
                    >
                      <option value="">{tr('Not specified')}</option>
                      {feedOptions.map((feed) => (
                        <option key={feed.id} value={feed.id}>
                          {feed.label}
                        </option>
                      ))}
                    </select>
                  </label>
                  <label className="block md:col-span-1">
                    <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Method')}</span>
                    <select
                      className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                      value={form.feeding_method}
                      onChange={(event) => handleChange('feeding_method', event.target.value)}
                      disabled={!canCreateFeedLog || saving}
                    >
                      <option value="manual">{tr('manual')}</option>
                      <option value="auto_feeder">{tr('auto_feeder')}</option>
                      <option value="broadcast">{tr('broadcast')}</option>
                      <option value="tray">{tr('tray')}</option>
                      <option value="other">{tr('other')}</option>
                    </select>
                  </label>
                  <label className="block md:col-span-1">
                    <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Appetite')}</span>
                    <select
                      className="h-11 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                      value={form.appetite}
                      onChange={(event) => handleChange('appetite', event.target.value)}
                      disabled={!canCreateFeedLog || saving}
                    >
                      <option value="low">{tr('low')}</option>
                      <option value="normal">{tr('normal')}</option>
                      <option value="high">{tr('high')}</option>
                    </select>
                  </label>
                </div>

                <label className="block">
                  <span className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-200">{tr('Notes')}</span>
                  <textarea
                    className="min-h-[104px] w-full rounded-xl border border-slate-300 bg-white px-3 py-3 text-sm shadow-sm focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/30 dark:border-dark-700 dark:bg-dark-800"
                    placeholder={tr('Optional observation, e.g. fish surfaced quickly, mild leftovers, weather change')}
                    value={form.notes}
                    onChange={(event) => handleChange('notes', event.target.value)}
                    disabled={!canCreateFeedLog || saving}
                  />
                </label>

                {!canCreateFeedLog && (
                  <p className="rounded-xl bg-amber-50 px-3 py-2 text-sm text-amber-800 ring-1 ring-amber-200">
                    {tr('Your role can view feeding logs but cannot create new records')}
                  </p>
                )}

                <div className="flex flex-wrap gap-3 pt-2">
                  <BaseButton
                    color="info"
                    disabled={!canCreateFeedLog || saving}
                    label={saving ? 'Saving' : 'Save feeding record'}
                    type="submit"
                  />
                  <BaseButton color="whiteDark" href="/feeding_logs/feeding_logs-new" label="Advanced form" />
                </div>
              </form>
            )}
          </CardBox>

          <div className="grid gap-6 lg:grid-cols-[1fr_0.85fr] xl:grid-cols-1 2xl:grid-cols-[1fr_0.85fr]">
            <CardBox className="border-0 shadow-lg ring-1 ring-slate-200/80 dark:ring-dark-700">
              <div className="mb-5 flex items-center justify-between gap-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-sky-600">{tr('Activity stream')}</p>
                  <h3 className="mt-1 text-2xl font-bold text-slate-900 dark:text-white">{tr('Latest feeding logs')}</h3>
                </div>
                <BaseButton color="whiteDark" label="Refresh" onClick={fetchWorkspace} small />
              </div>

              {loading ? (
                <div className="rounded-2xl bg-slate-50 p-6 text-sm text-slate-500">{tr('Loading latest records')}</div>
              ) : logs.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-8 text-center">
                  <BaseIcon path={mdiClipboardTextClock} size="40" className="mx-auto text-slate-400" />
                  <p className="mt-3 font-semibold text-slate-900">{tr('No feeding logs yet')}</p>
                  <p className="mt-1 text-sm text-slate-500">{tr('Use the quick input form to create the first daily operation record')}</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {logs.map((log) => {
                    const isSelected = selectedLog?.id === log.id
                    const appetiteClass = statusStyles[log.appetite] || statusStyles.normal

                    return (
                      <button
                        key={log.id}
                        className={`w-full rounded-2xl border p-4 text-left transition hover:-translate-y-0.5 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-teal-500/40 ${
                          isSelected ? 'border-teal-400 bg-teal-50/80' : 'border-slate-200 bg-white dark:border-dark-700 dark:bg-dark-900'
                        }`}
                        type="button"
                        onClick={() => setSelectedLog(log)}
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="font-bold text-slate-900 dark:text-white">{log.batch?.batch_code || tr('Unassigned batch')}</p>
                            <p className="mt-1 text-sm text-slate-500">{formatDateTime(log.fed_at, locale, tr('Not scheduled'))} • {tr(log.feeding_method || 'manual')}</p>
                          </div>
                          <span className={`rounded-full px-2.5 py-1 text-xs font-semibold capitalize ring-1 ${appetiteClass}`}>
                            {tr(log.appetite || 'normal')}
                          </span>
                        </div>
                        <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
                          <div className="rounded-xl bg-slate-50 p-3 dark:bg-dark-800">
                            <span className="block text-xs uppercase tracking-wide text-slate-400">{tr('Quantity')}</span>
                            <strong>{formatQuantity(log.quantity_kg, locale)}</strong>
                          </div>
                          <div className="rounded-xl bg-slate-50 p-3 dark:bg-dark-800">
                            <span className="block text-xs uppercase tracking-wide text-slate-400">{tr('Feed')}</span>
                            <strong>{log.feed_product?.product_name || tr('Not specified')}</strong>
                          </div>
                        </div>
                      </button>
                    )
                  })}
                </div>
              )}
            </CardBox>

            <CardBox className="border-0 bg-slate-950 text-white shadow-lg ring-1 ring-slate-800">
              <div className="mb-5 flex items-center justify-between gap-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-300">{tr('Detail')}</p>
                  <h3 className="mt-1 text-2xl font-bold">{tr('Record snapshot')}</h3>
                </div>
                <span className="rounded-2xl bg-cyan-400/10 p-3 text-cyan-200 ring-1 ring-cyan-300/20">
                  <BaseIcon path={mdiWaterPercent} size="24" />
                </span>
              </div>

              {selectedLog ? (
                <div className="space-y-4">
                  <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/10">
                    <p className="text-sm text-slate-300">{tr('Batch')}</p>
                    <p className="mt-1 text-2xl font-black">{selectedLog.batch?.batch_code || tr('Unassigned batch')}</p>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/10">
                      <p className="text-xs uppercase tracking-wide text-slate-400">{tr('Quantity')}</p>
                      <p className="mt-1 text-xl font-bold">{formatQuantity(selectedLog.quantity_kg, locale)}</p>
                    </div>
                    <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/10">
                      <p className="text-xs uppercase tracking-wide text-slate-400">{tr('Appetite')}</p>
                      <p className="mt-1 text-xl font-bold capitalize">{tr(selectedLog.appetite || 'normal')}</p>
                    </div>
                  </div>
                  <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/10">
                    <p className="text-xs uppercase tracking-wide text-slate-400">{tr('Recorded')}</p>
                    <p className="mt-1 font-semibold">{formatDateTime(selectedLog.fed_at, locale, tr('Not scheduled'))} {tr('by')} {getRecorder(selectedLog, tr('Team member'))}</p>
                  </div>
                  <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/10">
                    <p className="text-xs uppercase tracking-wide text-slate-400">{tr('Notes')}</p>
                    <p className="mt-2 text-sm leading-6 text-slate-200">{selectedLog.notes || tr('No notes added for this operation')}</p>
                  </div>
                  <div className="flex flex-wrap gap-3 pt-2">
                    <BaseButton color="info" href={`/feeding_logs/${selectedLog.id}`} label="Open detail" />
                    <BaseButton color="whiteDark" href="/marketplace_listings/marketplace_listings-list" label="Marketplace" />
                  </div>
                </div>
              ) : (
                <div className="rounded-2xl border border-dashed border-white/20 p-8 text-center text-slate-300">
                  {tr('Select a feeding log to inspect its farm-ready details')}
                </div>
              )}
            </CardBox>
          </div>
        </div>

        <section className="mt-6 grid gap-4 md:grid-cols-3">
          {[
            { icon: mdiFish, title: 'Batch context', text: 'Every record is tied to generated batch CRUD for traceability.' },
            { icon: mdiCalendarCheck, title: 'Daily rhythm', text: 'Fast input supports the staff workflow farmers repeat every shift.' },
            { icon: mdiStorefront, title: 'Marketplace ready', text: 'Operational records are one step away from harvest, listing, order, and transaction flows.' },
          ].map((item) => (
            <div key={item.title} className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200 dark:bg-dark-900 dark:ring-dark-700">
              <BaseIcon path={item.icon} size="28" className="text-teal-600" />
              <h4 className="mt-3 font-bold text-slate-900 dark:text-white">{tr(item.title)}</h4>
              <p className="mt-1 text-sm leading-6 text-slate-500">{tr(item.text)}</p>
            </div>
          ))}
        </section>
      </SectionMain>
    </>
  )
}

FarmOpsPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission="READ_FEEDING_LOGS">{page}</LayoutAuthenticated>
}

export default FarmOpsPage
