'use client';

import { useState } from 'react';
import { Plus, MoreVertical, Pencil, Trash2, Search } from 'lucide-react';
import { Card, CardContent } from '@/figma-make/components/base/card';
import { Button } from '@/figma-make/components/base/button';
import { Label } from '@/figma-make/components/base/label';
import { Input } from '@/figma-make/components/base/input';
import { Badge } from '@/figma-make/components/base/badge';
import { MultiSelect } from '@/figma-make/components/base/multi-select';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/figma-make/components/base/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/figma-make/components/base/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/figma-make/components/base/alert-dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/figma-make/components/base/dropdown-menu';
import { toast } from 'sonner';
import useSWR from 'swr';
import { DailyChecklistKandangApi } from '@/services/api/daily-checklist/kandang';
import Table from '@/components/Table';
import { DailyChecklistKandang } from '@/types/api/daily-checklist/kandang';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ColumnDef } from '@tanstack/react-table';
import { useSelect } from '@/components/input/SelectInput';
import { LocationApi } from '@/services/api/master-data';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { UserApi } from '@/services/api/user';

export function MasterKandangContent() {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      location_id: '',
      status: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      search: 'search',
      location_id: 'location_id',
    },
  });

  const {
    data: dailyChecklistKandangs,
    isLoading: isLoadingDailyChecklistKandangs,
    mutate: refreshDailyChecklistKandangs,
  } = useSWR(
    `${DailyChecklistKandangApi.basePath}${getTableFilterQueryString()}`,
    DailyChecklistKandangApi.getAllFetcher,
    {
      keepPreviousData: true,
    }
  );
  const { options: locationOptions } = useSelect(
    LocationApi.basePath,
    'id',
    'name',
    'search',
    {
      page: '1',
      limit: '100',
    }
  );

  const { options: picOptions } = useSelect(
    UserApi.basePath,
    'id',
    'name',
    'search',
    {
      page: '1',
      limit: '100',
    }
  );

  const [showModal, setShowModal] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [kandangToDelete, setKandangToDelete] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [modalMode, setModalMode] = useState<'create' | 'edit'>('create');
  const [kandangForm, setKandangForm] = useState({
    id: 0,
    name: '',
    location_id: 0,
    pic_id: 0,
    // recording_kandangs: [] as number[],
  });

  const dailyChecklistKandangColumns: ColumnDef<DailyChecklistKandang>[] = [
    {
      id: 'name',
      header: 'Nama',
      accessorKey: 'name',
      enableSorting: false,
    },
    {
      id: 'location',
      header: 'Lokasi',
      accessorKey: 'location',
      enableSorting: false,
      cell: ({ row }) => row.original.location.name ?? '-',
    },
    {
      id: 'pic',
      header: 'PIC',
      accessorKey: 'pic',
      enableSorting: false,
      cell: ({ row }) => row.original.pic.name ?? '-',
    },
    {
      id: 'recording_kandangs',
      header: 'Kandang Recording',
      accessorKey: 'recording_kandangs',
      enableSorting: false,
      cell: ({ row }) =>
        row.original.recording_kandangs?.length > 0
          ? row.original.recording_kandangs.map((item) => item.name).join(', ')
          : '-',
    },
    {
      id: 'action',
      header: 'Aksi',
      accessorKey: 'action',
      enableSorting: false,
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant='ghost'
              size='sm'
              className='h-8 w-8 p-0 hover:bg-gray-100'
            >
              <MoreVertical className='h-4 w-4 text-gray-600' />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align='end'>
            <DropdownMenuItem onClick={() => handleEdit(row.original)}>
              <Pencil className='mr-2 h-4 w-4' />
              Edit
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => handleDeleteClick(row.original.id)}
              className='text-red-600'
            >
              <Trash2 className='mr-2 h-4 w-4' />
              Hapus
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const handleAdd = () => {
    setModalMode('create');
    setKandangForm({
      id: 0,
      name: '',
      location_id: 0,
      pic_id: 0,
      //  recording_kandangs: []
    });
    setShowModal(true);
  };

  const handleEdit = (dailyChecklistKandang: DailyChecklistKandang) => {
    setModalMode('edit');
    setKandangForm({
      id: dailyChecklistKandang.id,
      name: dailyChecklistKandang.name,
      location_id: dailyChecklistKandang.location.id,
      pic_id: dailyChecklistKandang.pic.id,
      // recording_kandangs:
      //   dailyChecklistKandang.recording_kandangs.map((item) => item.id) ?? [],
    });
    setShowModal(true);
  };

  const handleSave = async () => {
    if (!kandangForm.name.trim()) {
      toast.error('Nama harus diisi');
      return;
    }

    if (!kandangForm.location_id) {
      toast.error('Lokasi wajib diisi');
      return;
    }

    // if (!kandangForm.recording_kandangs.length) {
    //   toast.error('Kandang recording wajib diisi');
    //   return;
    // }

    setLoading(true);

    try {
      if (modalMode === 'create') {
        const createDailyChecklistKandangResponse =
          await DailyChecklistKandangApi.create({
            name: kandangForm.name.trim(),
            location_id: kandangForm.location_id,
            pic_id: kandangForm.pic_id,
            // recording_kandang_ids: kandangForm.recording_kandangs,
          });

        if (isResponseError(createDailyChecklistKandangResponse)) {
          console.error(
            'Error creating kandang:',
            createDailyChecklistKandangResponse.message
          );
          toast.error('Gagal menambahkan kandang');
          return;
        }

        refreshDailyChecklistKandangs();
        toast.success('Kandang berhasil ditambahkan');
      } else {
        const updateDailyChecklistKandangResponse =
          await DailyChecklistKandangApi.update(kandangForm.id, {
            name: kandangForm.name.trim(),
            location_id: kandangForm.location_id,
            pic_id: kandangForm.pic_id,
            // recording_kandang_ids: kandangForm.recording_kandangs,
          });

        if (isResponseError(updateDailyChecklistKandangResponse)) {
          console.error(
            'Error updating kandang:',
            updateDailyChecklistKandangResponse.message
          );
          toast.error('Gagal menambahkan Kandang');
          return;
        }

        refreshDailyChecklistKandangs();
        toast.success('Kandang berhasil diubah');
      }

      setShowModal(false);
      setKandangForm({
        id: 0,
        name: '',
        location_id: 0,
        pic_id: 0,
        // recording_kandangs: [],
      });
    } catch (error) {
      console.error('Error saving kandang:', error);
      toast.error('Terjadi kesalahan saat menyimpan kandang');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteClick = (kandangId: number) => {
    setKandangToDelete(kandangId);
    setShowDeleteConfirm(true);
  };

  const handleConfirmDelete = async () => {
    if (!kandangToDelete) return;

    setLoading(true);

    try {
      const deleteKandangResponse =
        await DailyChecklistKandangApi.delete(kandangToDelete);

      if (isResponseError(deleteKandangResponse)) {
        console.error('Error deleting kandang:', deleteKandangResponse.message);
        toast.error('Gagal menghapus kandang');
        return;
      }

      refreshDailyChecklistKandangs();
      toast.success('Kandang berhasil dihapus');
      setShowDeleteConfirm(false);
      setKandangToDelete(null);
    } catch (error) {
      console.error('Error deleting kandang:', error);
      toast.error('Terjadi kesalahan saat menghapus kandang');
    } finally {
      setLoading(false);
    }
  };

  if (isLoadingDailyChecklistKandangs && !dailyChecklistKandangs) {
    return (
      <div className='min-h-screen'>
        <div className='p-6'>
          <div className='mb-6'>
            <h1 className='text-2xl font-semibold text-gray-900'>
              Master Kandang
            </h1>
            <p className='text-sm text-gray-600 mt-1'>
              Master Data • <span className='text-[#0069e0]'>Kandang</span>
            </p>
          </div>
          <Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
            <CardContent className='p-12 text-center text-gray-500'>
              Memuat data...
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className='min-h-screen'>
      <div className='p-6'>
        {/* Page Title */}
        <div className='mb-6'>
          <h1 className='text-2xl font-semibold text-gray-900'>
            Master Kandang
          </h1>
          <p className='text-sm text-gray-600 mt-1'>
            Master Data • <span className='text-[#0069e0]'>Kandang</span>
          </p>
        </div>

        {/* Main Card */}
        <Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
          <CardContent className='p-0'>
            {/* Single Toolbar Row */}
            <div className='flex flex-wrap items-center justify-between gap-4 p-6 border-b border-gray-200/60'>
              {/* LEFT: Search + Filters */}
              <div className='flex items-center gap-3 flex-wrap'>
                <div className='relative'>
                  <Search className='absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4' />

                  <DebouncedTextInput
                    name='search'
                    placeholder='Cari kandang...'
                    value={tableFilterState.search}
                    onChange={(e) => updateFilter('search', e.target.value)}
                    className={{
                      wrapper: 'w-full sm:w-[280px] border-gray-200',
                      inputWrapper: 'px-3 py-2 h-fit rounded-md',
                      input: 'text-sm',
                    }}
                    startAdornment={
                      <Search className='text-gray-400 w-4 h-4' />
                    }
                  />
                </div>

                <Select
                  value={tableFilterState.location_id}
                  onValueChange={(value) =>
                    updateFilter('location_id', value === 'all' ? '' : value)
                  }
                >
                  <SelectTrigger className='w-[180px] border-gray-200'>
                    <SelectValue placeholder='Semua Lokasi' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Semua Lokasi</SelectItem>
                    {locationOptions.map((kandang) => (
                      <SelectItem
                        key={kandang.value}
                        value={String(kandang.value)}
                      >
                        {kandang.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* RIGHT: Export + Add */}
              <div className='flex items-center gap-2 flex-wrap'>
                <Button
                  onClick={handleAdd}
                  className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
                >
                  <Plus className='w-4 h-4 mr-2' />
                  Tambah Kandang
                </Button>
              </div>
            </div>

            {/* Table */}
            <Table<DailyChecklistKandang>
              data={
                isResponseSuccess(dailyChecklistKandangs)
                  ? dailyChecklistKandangs?.data
                  : []
              }
              columns={dailyChecklistKandangColumns}
              pageSize={tableFilterState.pageSize}
              onPageSizeChange={setPageSize}
              rowOptions={[10, 20, 50, 100]}
              page={
                isResponseSuccess(dailyChecklistKandangs)
                  ? dailyChecklistKandangs?.meta?.page
                  : 0
              }
              totalItems={
                isResponseSuccess(dailyChecklistKandangs)
                  ? dailyChecklistKandangs?.meta?.total_results
                  : 0
              }
              onPageChange={setPage}
              isLoading={isLoadingDailyChecklistKandangs}
              className={{
                containerClassName: cn({
                  'w-full mb-20':
                    isResponseSuccess(dailyChecklistKandangs) &&
                    dailyChecklistKandangs?.data?.length === 0,
                }),
                tableWrapperClassName:
                  'overflow-x-auto border border-solid border-base-content/10 rounded-none',
                headerRowClassName: 'bg-gray-50/50',
                headerColumnClassName:
                  'text-left py-3.5 px-6 text-sm font-semibold text-gray-700',
                paginationClassName: 'px-4',
              }}
            />
          </CardContent>
        </Card>
      </div>

      {/* Add/Edit Modal */}
      <Dialog open={showModal} onOpenChange={setShowModal}>
        <DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
          <DialogHeader>
            <DialogTitle>
              {modalMode === 'create' ? 'Tambah Kandang' : 'Edit Kandang'}
            </DialogTitle>
            <DialogDescription>
              {modalMode === 'create'
                ? 'Masukkan detail Kandang baru'
                : 'Ubah detail Kandang'}
            </DialogDescription>
          </DialogHeader>
          <div className='space-y-4 py-4'>
            <div>
              <Label htmlFor='nama-kandang'>
                Nama Kandang <span className='text-red-500'>*</span>
              </Label>
              <Input
                id='nama-kandang'
                value={kandangForm.name}
                onChange={(e) =>
                  setKandangForm({ ...kandangForm, name: e.target.value })
                }
                placeholder='Masukkan nama Kandang'
                className='mt-1.5'
                disabled={loading}
              />
            </div>
            <div>
              <Label htmlFor='category'>
                Lokasi <span className='text-red-500'>*</span>
              </Label>
              <Select
                value={
                  kandangForm.location_id ? String(kandangForm.location_id) : ''
                }
                onValueChange={(value) =>
                  setKandangForm({ ...kandangForm, location_id: Number(value) })
                }
              >
                <SelectTrigger id='category' className='mt-1.5'>
                  <SelectValue placeholder='Pilih lokasi' />
                </SelectTrigger>
                <SelectContent>
                  {locationOptions.map((cat) => (
                    <SelectItem key={cat.value} value={String(cat.value)}>
                      {cat.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor='pic'>
                PIC <span className='text-red-500'>*</span>
              </Label>
              <Select
                value={kandangForm.pic_id ? String(kandangForm.pic_id) : ''}
                onValueChange={(value) =>
                  setKandangForm({ ...kandangForm, pic_id: Number(value) })
                }
              >
                <SelectTrigger id='pic' className='mt-1.5'>
                  <SelectValue placeholder='Pilih PIC' />
                </SelectTrigger>
                <SelectContent>
                  {picOptions.map((cat) => (
                    <SelectItem key={cat.value} value={String(cat.value)}>
                      {cat.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant='outline'
              onClick={() => setShowModal(false)}
              disabled={loading}
            >
              Batal
            </Button>
            <Button
              onClick={handleSave}
              disabled={loading}
              className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
            >
              {loading ? 'Menyimpan...' : 'Simpan'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent className='bg-white rounded-xl shadow-lg sm:max-w-md'>
          <AlertDialogHeader>
            <AlertDialogTitle>Hapus Kandang?</AlertDialogTitle>
            <AlertDialogDescription>
              Data Kandang akan dihapus secara permanen.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={loading}>Batal</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              disabled={loading}
              className='bg-red-600 hover:bg-red-700 text-white'
            >
              {loading ? 'Menghapus...' : 'Hapus'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
