import { Select, Space, Typography, Tag, Skeleton } 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;

interface CompanySwitcherProps {
  compact?: boolean;
}

export default function CompanySwitcher({ compact = false }: CompanySwitcherProps) {
  const { activeCompany, setActiveCompany } = useCompanyStore();
  const companies = useCompanyStore((state) => state.companies);

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

  if (companies.length === 0) {
    return <Skeleton.Input style={{ width: 200 }} active />;
  }

  return (
    <Space>
      <ShopOutlined style={{ fontSize: 18, color: '#1677ff' }} />
      <Select
        value={activeCompany?.id}
        onChange={handleCompanyChange}
        style={{ minWidth: compact ? 150 : 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>
  );
}
