'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Box, Card, Heading } from '@radix-ui/themes';
import { toast } from 'react-hot-toast'; // Import toast
import { handleError } from '@alga-psa/ui/lib/errorHandling';
import { Button } from '@alga-psa/ui/components/Button';
import { MoreVertical, Plus, Search, XCircle } from 'lucide-react';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@alga-psa/ui/components/DropdownMenu';
import { ContractLineDialog } from '../ContractLineDialog';
import { getContractLinePresets, deleteContractLinePreset } from '@alga-psa/billing/actions/contractLinePresetActions';
import { IContractLinePreset } from '@alga-psa/types';
import { getServiceTypesForSelection } from '@alga-psa/billing/actions'; // Added import for fetching types
import { DataTable } from '@alga-psa/ui/components/DataTable';
import { ColumnDefinition } from '@alga-psa/types';
import { CONTRACT_LINE_TYPE_VALUES } from '@alga-psa/billing/constants/billing';
import {
  useFormatBillingFrequency,
  useFormatContractLineType,
} from '@alga-psa/billing/hooks/useBillingEnumOptions';
import LoadingIndicator from '@alga-psa/ui/components/LoadingIndicator';
import { Input } from '@alga-psa/ui/components/Input';
import CustomSelect from '@alga-psa/ui/components/CustomSelect';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

const ContractLinesOverview: React.FC = () => {
  const { t } = useTranslation('msp/contract-lines');
  const formatBillingFrequency = useFormatBillingFrequency();
  const formatContractLineType = useFormatContractLineType();
  const [contractLines, setContractLines] = useState<IContractLinePreset[]>([]);
  const [editingPlan, setEditingPlan] = useState<IContractLinePreset | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [allServiceTypes, setAllServiceTypes] = useState<
    { id: string; name: string; is_standard: boolean }[]
  >([]); // Added state for service types
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const router = useRouter();

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // Handle page size change - reset to page 1
  const handlePageSizeChange = (newPageSize: number) => {
    setPageSize(newPageSize);
    setCurrentPage(1);
  };

  useEffect(() => {
    fetchContractLines();
    fetchAllServiceTypes(); // Fetch service types on mount
  }, []);

  const fetchContractLines = async () => {
    setIsLoading(true);
    try {
      const presets = await getContractLinePresets();
      setContractLines(presets);
      setError(null);
    } catch (error) {
      console.error('Error fetching contract line presets:', error);
      setError(t('overview.errors.failedToFetchContractLinePresets', {
        defaultValue: 'Failed to fetch contract line presets',
      }));
    } finally {
      setIsLoading(false);
    }
  };

  // Function to fetch all service types
  const fetchAllServiceTypes = async () => {
    try {
      const types = await getServiceTypesForSelection();
      setAllServiceTypes(types);
    } catch (error) {
      console.error('Error fetching service types:', error);
      // Optionally set an error state specific to service types
    }
  };

  const handleDeletePlan = async (presetId: string) => {
    try {
      await deleteContractLinePreset(presetId);
      await fetchContractLines();
      toast.success(t('overview.toast.contractLinePresetDeletedSuccessfully', {
        defaultValue: 'Contract line preset deleted successfully',
      }));
    } catch (error) {
      handleError(error, t('overview.errors.unexpectedDeleteError', {
        defaultValue: 'An unexpected error occurred while deleting the contract line preset.',
      }));
    }
  };

  // Filter contract line presets based on search term and contract line type
  const filteredContractLines = useMemo(() => {
    return contractLines.filter(preset => {
      // Search filter
      const matchesSearch = preset.preset_name?.toLowerCase().includes(searchTerm.toLowerCase());

      // Type filter
      const matchesType = filterType === 'all' || preset.contract_line_type === filterType;

      return matchesSearch && matchesType;
    });
  }, [contractLines, searchTerm, filterType]);

  // Contract line type filter options
  const typeFilterOptions = [
    { value: 'all', label: t('overview.filters.type.allTypes', { defaultValue: 'All types' }) },
    ...CONTRACT_LINE_TYPE_VALUES.map((value) => ({
      value,
      label: formatContractLineType(value),
    })),
  ];

  const contractLineColumns: ColumnDefinition<IContractLinePreset>[] = [
    {
      title: t('overview.columns.contractLineName', { defaultValue: 'Contract Line Name' }),
      dataIndex: 'preset_name',
    },
    {
      title: t('overview.columns.billingFrequency', { defaultValue: 'Billing Frequency' }),
      dataIndex: 'billing_frequency',
      render: (value) => formatBillingFrequency(value),
    },
    {
      title: t('overview.columns.contractLineType', { defaultValue: 'Contract Line Type' }),
      dataIndex: 'contract_line_type',
      render: (value) => formatContractLineType(value),
    },
    {
      title: t('overview.columns.actions', { defaultValue: 'Actions' }),
      dataIndex: 'preset_id',
      render: (value, record) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              id="contract-line-actions-menu"
              variant="ghost"
              className="h-8 w-8 p-0"
              onClick={(e) => e.stopPropagation()}
            >
              <span className="sr-only">
                {t('common.actions.openMenu', { defaultValue: 'Open menu' })}
              </span>
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              id="edit-contract-line-menu-item"
              onClick={(e) => {
                e.stopPropagation();
                if (record.preset_id) {
                  router.push(`/msp/billing?tab=contract-lines&presetId=${record.preset_id}`);
                }
              }}
            >
              {t('common.actions.edit', { defaultValue: 'Edit' })}
            </DropdownMenuItem>
            <DropdownMenuItem
              id="delete-contract-line-menu-item"
              className="text-red-600 focus:text-red-600"
              onClick={async (e) => {
                e.stopPropagation();
                if (record.preset_id) {
                  handleDeletePlan(record.preset_id);
                }
              }}
            >
              {t('common.actions.delete', { defaultValue: 'Delete' })}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const handleContractLineClick = (preset: IContractLinePreset) => {
    if (preset.preset_id) {
      router.push(`/msp/billing?tab=contract-lines&presetId=${preset.preset_id}`);
    }
  };

  return (
    <Card size="2">
      <Box p="4">
        <div className="flex justify-between items-center mb-4">
          <Heading as="h3" size="4">
            {t('overview.heading', { defaultValue: 'Contract Line Presets' })}
          </Heading>
          <ContractLineDialog
            onPlanAdded={(newPresetId) => {
              if (newPresetId) {
                // Refresh the contract lines list to show the new preset
                fetchContractLines();
              }
            }}
            editingPlan={editingPlan}
            onClose={() => setEditingPlan(null)}
            triggerButton={
              <Button id='add-contract-line-button'>
                <Plus className="h-4 w-4 mr-2" />
                {t('overview.actions.addContractLinePreset', { defaultValue: 'Add Contract Line Preset' })}
              </Button>
            }
            allServiceTypes={allServiceTypes} // Pass the fetched service types
          />
        </div>

        {error && (
          <Alert variant="destructive" className="mb-4">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* Filter section */}
        <div className="mb-4 flex flex-wrap items-center gap-2">
          {/* Search bar */}
          <div className="relative">
            <Input
              id="contract-line-search"
              type="text"
              placeholder={t('overview.filters.searchPlaceholder', {
                defaultValue: 'Search contract line presets',
              })}
              className="pl-10 pr-4 py-2 w-64"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <Search size={20} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
          </div>

          {/* Type filter */}
          <div className="relative z-10">
            <CustomSelect
              id="contract-line-type-filter"
              options={typeFilterOptions}
              value={filterType}
              onValueChange={(value) => setFilterType(value)}
              placeholder={t('overview.filters.type.selectTypePlaceholder', {
                defaultValue: 'Select type',
              })}
              customStyles={{
                content: 'mt-1'
              }}
            />
          </div>

          {/* Clear filters button */}
          {(searchTerm || filterType !== 'all') && (
            <Button
              id="clear-contract-line-filters-button"
              variant="outline"
              size="sm"
              onClick={() => {
                setSearchTerm('');
                setFilterType('all');
              }}
              className="flex items-center gap-1 bg-card"
            >
              <XCircle className="h-4 w-4" />
              <span>{t('common.actions.reset', { defaultValue: 'Reset' })}</span>
            </Button>
          )}
        </div>

        {isLoading ? (
          <LoadingIndicator
            layout="stacked"
            className="py-10 text-muted-foreground"
            spinnerProps={{ size: 'md' }}
            text={t('overview.loading', { defaultValue: 'Loading contract line presets' })}
          />
        ) : (
          <DataTable
            data={filteredContractLines.filter(preset => preset.preset_id !== undefined)}
            columns={contractLineColumns}
            pagination={true}
            currentPage={currentPage}
            onPageChange={setCurrentPage}
            pageSize={pageSize}
            onItemsPerPageChange={handlePageSizeChange}
            onRowClick={handleContractLineClick}
            rowClassName={() => "cursor-pointer"}
          />
        )}
      </Box>
    </Card>
  );
};

export default ContractLinesOverview;
