import { Select, Space, Typography, Tag } from 'antd';
import { ShopOutlined } from '@ant-design/icons';
import { useCompanyStore } from '@/stores/companyStore';
import { formatCVR } from '@/lib/formatters';
import type { Company } from '@/types/accounting';

const { Text } = Typography;

// Mock data - will be replaced with API call
const mockCompanies: Company[] = [
  {
    id: '1',
    name: 'Demo Virksomhed ApS',
    cvr: '12345678',
    address: 'Hovedgaden 1',
    city: 'Koebenhavn',
    postalCode: '1000',
    country: 'DK',
    fiscalYearStart: 1,
    currency: 'DKK',
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01',
  },
  {
    id: '2',
    name: 'Anden Virksomhed A/S',
    cvr: '87654321',
    address: 'Sidegaden 2',
    city: 'Aarhus',
    postalCode: '8000',
    country: 'DK',
    fiscalYearStart: 7,
    currency: 'DKK',
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01',
  },
];

export default function CompanySwitcher() {
  const { activeCompany, setActiveCompany, setCompanies } = useCompanyStore();

  // Initialize with mock data if needed
  if (useCompanyStore.getState().companies.length === 0) {
    setCompanies(mockCompanies);
    if (!activeCompany) {
      setActiveCompany(mockCompanies[0]);
    }
  }

  const companies = useCompanyStore((state) => state.companies);

  const handleCompanyChange = (companyId: string) => {
    const company = companies.find((c) => c.id === companyId);
    if (company) {
      setActiveCompany(company);
    }
  };

  return (
    <Space>
      <ShopOutlined style={{ fontSize: 18, color: '#1677ff' }} />
      <Select
        value={activeCompany?.id}
        onChange={handleCompanyChange}
        style={{ minWidth: 280 }}
        optionLabelProp="label"
        popupMatchSelectWidth={false}
        options={companies.map((company) => ({
          value: company.id,
          label: company.name,
          company,
        }))}
        optionRender={(option) => {
          const company = option.data.company as Company;
          return (
            <Space direction="vertical" size={0} style={{ padding: '4px 0' }}>
              <Space>
                <Text strong>{company.name}</Text>
                {company.id === activeCompany?.id && (
                  <Tag color="blue" style={{ marginLeft: 8 }}>
                    Aktiv
                  </Tag>
                )}
              </Space>
              <Text type="secondary" style={{ fontSize: 12 }}>
                CVR: {formatCVR(company.cvr)}
              </Text>
            </Space>
          );
        }}
      />
    </Space>
  );
}
