// FiscalYearSelector - Dropdown for selecting active fiscal year (regnskabsår)

import { useState, useEffect } from 'react';
import { Select, Space, Typography, Tag, Divider, Button } from 'antd';
import {
  CalendarOutlined,
  PlusOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  MinusCircleOutlined,
  LockOutlined,
} from '@ant-design/icons';
import { usePeriodStore } from '@/stores/periodStore';
import type { FiscalYear } from '@/types/periods';
import { formatDateShort } from '@/lib/formatters';
import CreateFiscalYearModal from '@/components/modals/CreateFiscalYearModal';

const { Text } = Typography;

// Mock data - will be replaced with API call
const mockFiscalYears: FiscalYear[] = [
  {
    id: 'fy-2025',
    companyId: '1',
    name: '2025',
    startDate: '2025-01-01',
    endDate: '2025-12-31',
    status: 'open',
    openingBalancePosted: true,
    createdAt: '2025-01-01',
    updatedAt: '2025-01-01',
  },
  {
    id: 'fy-2024',
    companyId: '1',
    name: '2024',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    status: 'closed',
    closingDate: '2025-01-15',
    closedBy: 'user-1',
    openingBalancePosted: true,
    createdAt: '2024-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 'fy-2023',
    companyId: '1',
    name: '2023',
    startDate: '2023-01-01',
    endDate: '2023-12-31',
    status: 'locked',
    closingDate: '2024-01-20',
    closedBy: 'user-1',
    openingBalancePosted: true,
    createdAt: '2023-01-01',
    updatedAt: '2024-01-20',
  },
];

/**
 * Status badge configuration
 */
const STATUS_CONFIG: Record<FiscalYear['status'], {
  color: string;
  icon: React.ReactNode;
  label: string;
}> = {
  open: {
    color: 'success',
    icon: <CheckCircleOutlined />,
    label: 'Åben',
  },
  closed: {
    color: 'warning',
    icon: <MinusCircleOutlined />,
    label: 'Lukket',
  },
  locked: {
    color: 'error',
    icon: <LockOutlined />,
    label: 'Låst',
  },
};

interface FiscalYearSelectorProps {
  onCreateNew?: () => void;
  onManage?: () => void;
}

export default function FiscalYearSelector({ onCreateNew, onManage }: FiscalYearSelectorProps) {
  const {
    fiscalYears,
    currentFiscalYear,
    setFiscalYears,
    setCurrentFiscalYear,
  } = usePeriodStore();

  const [createModalOpen, setCreateModalOpen] = useState(false);

  // Initialize with mock data if needed (will be replaced with API call)
  useEffect(() => {
    if (fiscalYears.length === 0) {
      setFiscalYears(mockFiscalYears);
    }
  }, [fiscalYears.length, setFiscalYears]);

  // Set default fiscal year if none selected
  useEffect(() => {
    if (fiscalYears.length > 0 && !currentFiscalYear) {
      // Default to most recent open year, or first year
      const openYear = fiscalYears.find(y => y.status === 'open');
      setCurrentFiscalYear(openYear || fiscalYears[0]);
    }
  }, [fiscalYears, currentFiscalYear, setCurrentFiscalYear]);

  const handleFiscalYearChange = (yearId: string) => {
    const year = fiscalYears.find((y) => y.id === yearId);
    if (year) {
      setCurrentFiscalYear(year);
    }
  };

  const handleCreateNew = () => {
    if (onCreateNew) {
      onCreateNew();
    } else {
      setCreateModalOpen(true);
    }
  };

  const handleCloseCreateModal = () => {
    setCreateModalOpen(false);
  };

  const handleCreateSuccess = (newYear: FiscalYear) => {
    setCurrentFiscalYear(newYear);
    setCreateModalOpen(false);
  };

  const handleManage = () => {
    if (onManage) {
      onManage();
    } else {
      // Navigate to settings page
      console.log('Navigate to fiscal year settings');
    }
  };

  // Sort fiscal years by start date descending (newest first)
  const sortedYears = [...fiscalYears].sort(
    (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
  );

  return (
    <Space>
      <CalendarOutlined style={{ fontSize: 16, color: '#8c8c8c' }} />
      <Select
        value={currentFiscalYear?.id}
        onChange={handleFiscalYearChange}
        style={{ minWidth: 200 }}
        optionLabelProp="label"
        popupMatchSelectWidth={false}
        dropdownRender={(menu) => (
          <>
            {menu}
            <Divider style={{ margin: '8px 0' }} />
            <Space style={{ padding: '0 8px 8px' }}>
              <Button
                type="text"
                icon={<PlusOutlined />}
                onClick={handleCreateNew}
                size="small"
              >
                Opret nyt regnskabsår
              </Button>
              <Button
                type="text"
                icon={<SettingOutlined />}
                onClick={handleManage}
                size="small"
              >
                Administrer
              </Button>
            </Space>
          </>
        )}
        options={sortedYears.map((year) => ({
          value: year.id,
          label: `Regnskabsår ${year.name}`,
          year,
        }))}
        optionRender={(option) => {
          const year = option.data.year;
          // Type guard - ensure year exists and has required properties
          if (!year || typeof year !== 'object' || !('status' in year)) {
            return null;
          }
          const fiscalYear = year as FiscalYear;
          const statusConfig = STATUS_CONFIG[fiscalYear.status];

          return (
            <Space
              direction="vertical"
              size={0}
              style={{ padding: '4px 0', width: '100%' }}
            >
              <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                <Text strong>{fiscalYear.name}</Text>
                <Tag
                  color={statusConfig.color}
                  icon={statusConfig.icon}
                  style={{ marginLeft: 8 }}
                >
                  {statusConfig.label}
                </Tag>
              </Space>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {formatDateShort(fiscalYear.startDate)} - {formatDateShort(fiscalYear.endDate)}
              </Text>
            </Space>
          );
        }}
      />
      {currentFiscalYear && (
        <Tag
          color={STATUS_CONFIG[currentFiscalYear.status].color}
          icon={STATUS_CONFIG[currentFiscalYear.status].icon}
        >
          {STATUS_CONFIG[currentFiscalYear.status].label}
        </Tag>
      )}

      {/* Create Fiscal Year Modal */}
      <CreateFiscalYearModal
        open={createModalOpen}
        onClose={handleCloseCreateModal}
        onSuccess={handleCreateSuccess}
      />
    </Space>
  );
}
