// AccountQuickPicker - Quick account selection with favorites

import { useState, useMemo } from 'react';
import { Select, Button, Space, Tag, Typography, Divider, Input } from 'antd';
import { StarOutlined, StarFilled, SearchOutlined } from '@ant-design/icons';
import type { Account } from '@/types/accounting';
import type { VATCode } from '@/types/vat';
import { VAT_CODE_CONFIG } from '@/lib/vatCodes';
import { useTopFavorites, useSimpleBookingStore } from '@/stores/simpleBookingStore';

const { Text } = Typography;

interface AccountOption {
  id: string;
  accountNumber: string;
  name: string;
  type: string;
}

interface AccountQuickPickerProps {
  accounts: AccountOption[];
  value?: string;
  onChange: (accountId: string, account: AccountOption) => void;
  isExpense?: boolean;
  favoriteLimit?: number;
  placeholder?: string;
}

export function AccountQuickPicker({
  accounts,
  value,
  onChange,
  isExpense = true,
  favoriteLimit = 6,
  placeholder = 'Soeg efter konto...',
}: AccountQuickPickerProps) {
  const [searchValue, setSearchValue] = useState('');
  const topFavorites = useTopFavorites(favoriteLimit);
  const { addFavoriteAccount, removeFavoriteAccount, incrementFavoriteUsage, favoriteAccounts } = useSimpleBookingStore();

  // Filter accounts based on search
  const filteredAccounts = useMemo(() => {
    if (!searchValue) return accounts;
    const search = searchValue.toLowerCase();
    return accounts.filter(
      (account) =>
        account.accountNumber.toLowerCase().includes(search) ||
        account.name.toLowerCase().includes(search)
    );
  }, [accounts, searchValue]);

  // Check if an account is a favorite
  const isFavorite = (accountId: string) =>
    favoriteAccounts.some((f) => f.accountId === accountId);

  // Handle account selection
  const handleSelect = (accountId: string) => {
    const account = accounts.find((a) => a.id === accountId);
    if (account) {
      onChange(accountId, account);
      // Increment favorite usage if it's a favorite
      if (isFavorite(accountId)) {
        incrementFavoriteUsage(accountId);
      }
    }
  };

  // Handle favorite toggle
  const handleToggleFavorite = (account: AccountOption, event: React.MouseEvent) => {
    event.stopPropagation();
    if (isFavorite(account.id)) {
      removeFavoriteAccount(account.id);
    } else {
      addFavoriteAccount({
        accountId: account.id,
        accountNumber: account.accountNumber,
        accountName: account.name,
        defaultVATCode: isExpense ? 'K25' : 'S25',
      });
    }
  };

  // Get quick buttons for favorites
  const quickButtons = topFavorites.map((fav) => {
    const account = accounts.find((a) => a.id === fav.accountId);
    if (!account) return null;
    return (
      <Button
        key={fav.id}
        size="small"
        type={value === fav.accountId ? 'primary' : 'default'}
        onClick={() => handleSelect(fav.accountId)}
        style={{ marginRight: 4, marginBottom: 4 }}
      >
        {account.accountNumber} {account.name.substring(0, 12)}
        {account.name.length > 12 ? '...' : ''}
      </Button>
    );
  }).filter(Boolean);

  // Select options
  const selectOptions = filteredAccounts.map((account) => ({
    value: account.id,
    label: (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span>
          <Text strong style={{ marginRight: 8 }}>{account.accountNumber}</Text>
          {account.name}
        </span>
        <span onClick={(e) => handleToggleFavorite(account, e)} style={{ cursor: 'pointer' }}>
          {isFavorite(account.id) ? (
            <StarFilled style={{ color: '#faad14' }} />
          ) : (
            <StarOutlined style={{ color: '#d9d9d9' }} />
          )}
        </span>
      </div>
    ),
    searchValue: `${account.accountNumber} ${account.name}`,
  }));

  return (
    <div className="account-quick-picker">
      {/* Quick favorite buttons */}
      {quickButtons.length > 0 && (
        <div style={{ marginBottom: 8 }}>
          <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 4 }}>
            Hurtige valg:
          </Text>
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {quickButtons}
          </div>
        </div>
      )}

      {/* Full search select */}
      <Select
        showSearch
        style={{ width: '100%' }}
        placeholder={placeholder}
        value={value}
        onChange={handleSelect}
        onSearch={setSearchValue}
        filterOption={false}
        options={selectOptions}
        optionFilterProp="searchValue"
        suffixIcon={<SearchOutlined />}
        notFoundContent={
          <div style={{ padding: '8px', textAlign: 'center' }}>
            <Text type="secondary">Ingen konti fundet</Text>
          </div>
        }
      />
    </div>
  );
}

interface VATCodePickerProps {
  value?: VATCode;
  onChange: (code: VATCode) => void;
  isExpense?: boolean;
  showDescription?: boolean;
}

export function VATCodePicker({
  value,
  onChange,
  isExpense = true,
  showDescription = false,
}: VATCodePickerProps) {
  // Get relevant VAT codes based on transaction type
  const relevantCodes = useMemo(() => {
    if (isExpense) {
      // Input VAT codes for expenses
      return ['K25', 'EU_VARE', 'EU_YDELSE', 'NONE'] as VATCode[];
    } else {
      // Output VAT codes for income
      return ['S25', 'MOMSFRI', 'EKSPORT', 'NONE'] as VATCode[];
    }
  }, [isExpense]);

  const options = relevantCodes.map((code) => {
    const config = VAT_CODE_CONFIG[code];
    return {
      value: code,
      label: (
        <div>
          <Text strong style={{ marginRight: 8 }}>{code}</Text>
          {config.nameDanish}
          {config.rate > 0 && (
            <Tag size="small" style={{ marginLeft: 8 }}>
              {(config.rate * 100).toFixed(0)}%
            </Tag>
          )}
        </div>
      ),
    };
  });

  const selectedConfig = value ? VAT_CODE_CONFIG[value] : null;

  return (
    <div className="vat-code-picker">
      <Select
        style={{ width: '100%' }}
        placeholder="Vaelg momskode"
        value={value}
        onChange={onChange}
        options={options}
      />
      {showDescription && selectedConfig && (
        <Text type="secondary" style={{ fontSize: 12, display: 'block', marginTop: 4 }}>
          {selectedConfig.description}
        </Text>
      )}
    </div>
  );
}

export default AccountQuickPicker;
