// CreateFiscalYearModal - Modal for creating a new fiscal year (regnskabsår)

import { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  DatePicker,
  Input,
  Select,
  Alert,
  Space,
  Typography,
  Divider,
} from 'antd';
import {
  CalendarOutlined,
  InfoCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { usePeriodStore } from '@/stores/periodStore';
import { useCompanyStore } from '@/stores/companyStore';
import {
  getFiscalYearBoundaries,
  validateFiscalYearCreation,
} from '@/lib/fiscalYear';
import { generateAccountingPeriods } from '@/lib/periods';
import type { FiscalYear, PeriodFrequency } from '@/types/periods';

const { Text } = Typography;
const { RangePicker } = DatePicker;

interface CreateFiscalYearModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess?: (fiscalYear: FiscalYear) => void;
  suggestedDate?: string; // Pre-populate based on trigger context
  autoCreate?: boolean; // If true, show confirmation mode for auto-creation
}

interface FormValues {
  dateRange: [Dayjs, Dayjs];
  name: string;
  periodFrequency: PeriodFrequency;
}

export default function CreateFiscalYearModal({
  open,
  onClose,
  onSuccess,
  suggestedDate,
  autoCreate = false,
}: CreateFiscalYearModalProps) {
  const [form] = Form.useForm<FormValues>();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [validationResult, setValidationResult] = useState<ReturnType<typeof validateFiscalYearCreation> | null>(null);

  const { activeCompany } = useCompanyStore();
  const { fiscalYears, addFiscalYear, setPeriods, periods, setCurrentFiscalYear } = usePeriodStore();

  // Calculate suggested fiscal year boundaries
  useEffect(() => {
    if (open && activeCompany) {
      const dateToUse = suggestedDate || dayjs().format('YYYY-MM-DD');
      const boundaries = getFiscalYearBoundaries(
        dateToUse,
        activeCompany.fiscalYearStart
      );

      form.setFieldsValue({
        dateRange: [dayjs(boundaries.startDate), dayjs(boundaries.endDate)],
        name: boundaries.name,
        periodFrequency: 'monthly',
      });

      // Validate immediately
      handleValidation(boundaries.startDate, boundaries.endDate);
    }
  }, [open, activeCompany, suggestedDate, form]);

  const handleValidation = (startDate: string, endDate: string) => {
    const result = validateFiscalYearCreation(
      { startDate, endDate },
      fiscalYears
    );
    setValidationResult(result);
  };

  const handleDateRangeChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
    if (dates && dates[0] && dates[1]) {
      const startDate = dates[0].format('YYYY-MM-DD');
      const endDate = dates[1].format('YYYY-MM-DD');

      // Auto-update name
      const startYear = dates[0].year();
      const endYear = dates[1].year();
      const name = startYear === endYear ? `${startYear}` : `${startYear}/${endYear}`;
      form.setFieldValue('name', name);

      handleValidation(startDate, endDate);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setIsSubmitting(true);

      if (!activeCompany) {
        throw new Error('No active company');
      }

      const startDate = values.dateRange[0].format('YYYY-MM-DD');
      const endDate = values.dateRange[1].format('YYYY-MM-DD');

      // Create fiscal year object
      const newFiscalYear: FiscalYear = {
        id: `fy-${values.name}-${Date.now()}`,
        companyId: activeCompany.id,
        name: values.name,
        startDate,
        endDate,
        status: 'open',
        openingBalancePosted: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      // Generate accounting periods and add required fields
      const generatedPeriods = generateAccountingPeriods(newFiscalYear, values.periodFrequency);
      const now = new Date().toISOString();
      const newPeriods = generatedPeriods.map((p, idx) => ({
        ...p,
        id: `period-${newFiscalYear.id}-${idx + 1}`,
        createdAt: now,
        updatedAt: now,
      }));

      // Add to store
      addFiscalYear(newFiscalYear);
      setPeriods([...periods, ...newPeriods]);

      // Set as current if this is the first or most recent
      const allYears = [...fiscalYears, newFiscalYear];
      const sortedYears = allYears.sort(
        (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
      );
      if (sortedYears[0].id === newFiscalYear.id) {
        setCurrentFiscalYear(newFiscalYear);
      }

      onSuccess?.(newFiscalYear);
      onClose();
    } catch (error) {
      console.error('Failed to create fiscal year:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const hasErrors = validationResult?.errors && validationResult.errors.length > 0;
  const hasWarnings = validationResult?.warnings && validationResult.warnings.length > 0;

  return (
    <Modal
      title={
        <Space>
          <CalendarOutlined />
          {autoCreate ? 'Opret nyt regnskabsår?' : 'Opret nyt regnskabsår'}
        </Space>
      }
      open={open}
      onCancel={onClose}
      onOk={handleSubmit}
      okText={autoCreate ? 'Ja, opret regnskabsår' : 'Opret regnskabsår'}
      cancelText="Annuller"
      okButtonProps={{
        disabled: hasErrors || isSubmitting || !activeCompany,
        loading: isSubmitting,
      }}
      width={520}
      destroyOnClose
    >
      {!activeCompany && (
        <Alert
          type="error"
          message="Ingen virksomhed valgt"
          description="Du skal vælge en virksomhed før du kan oprette et regnskabsår."
          style={{ marginBottom: 16 }}
        />
      )}

      {autoCreate && suggestedDate && (
        <Alert
          type="info"
          icon={<InfoCircleOutlined />}
          message="Dato udenfor eksisterende regnskabsår"
          description={
            <Text>
              Datoen <strong>{dayjs(suggestedDate).format('D. MMMM YYYY')}</strong> falder
              udenfor eksisterende regnskabsår. Vil du oprette et nyt regnskabsår?
            </Text>
          }
          style={{ marginBottom: 16 }}
        />
      )}

      <Form
        form={form}
        layout="vertical"
        initialValues={{
          periodFrequency: 'monthly',
        }}
      >
        <Form.Item
          name="dateRange"
          label="Periode"
          rules={[{ required: true, message: 'Vælg start- og slutdato' }]}
        >
          <RangePicker
            style={{ width: '100%' }}
            format="DD-MM-YYYY"
            onChange={handleDateRangeChange}
          />
        </Form.Item>

        <Form.Item
          name="name"
          label="Navn"
          rules={[{ required: true, message: 'Indtast navn på regnskabsåret' }]}
        >
          <Input
            placeholder="f.eks. 2025 eller 2024/2025"
            prefix={<CalendarOutlined />}
          />
        </Form.Item>

        <Form.Item
          name="periodFrequency"
          label="Regnskabsperioder"
          tooltip="Hvor ofte skal regnskabsperioder oprettes?"
        >
          <Select
            options={[
              { value: 'monthly', label: 'Månedlig (12 perioder)' },
              { value: 'quarterly', label: 'Kvartalsvis (4 perioder)' },
              { value: 'half-yearly', label: 'Halvårlig (2 perioder)' },
              { value: 'yearly', label: 'Årlig (1 periode)' },
            ]}
          />
        </Form.Item>

        {/* Validation feedback */}
        {hasErrors && (
          <Alert
            type="error"
            message="Kan ikke oprette regnskabsår"
            description={
              <ul style={{ margin: 0, paddingLeft: 16 }}>
                {validationResult?.errors.map((err, idx) => (
                  <li key={idx}>{err.messageDanish}</li>
                ))}
              </ul>
            }
            style={{ marginTop: 16 }}
          />
        )}

        {hasWarnings && !hasErrors && (
          <Alert
            type="warning"
            icon={<WarningOutlined />}
            message="Advarsler"
            description={
              <ul style={{ margin: 0, paddingLeft: 16 }}>
                {validationResult?.warnings.map((warn, idx) => (
                  <li key={idx}>{warn.messageDanish}</li>
                ))}
              </ul>
            }
            style={{ marginTop: 16 }}
          />
        )}

        {validationResult?.isValid && !hasWarnings && (
          <Alert
            type="success"
            message="Klar til oprettelse"
            description="Regnskabsåret kan oprettes uden problemer."
            style={{ marginTop: 16 }}
          />
        )}
      </Form>

      {activeCompany && activeCompany.fiscalYearStart !== 1 && (
        <>
          <Divider style={{ margin: '16px 0' }} />
          <Text type="secondary" style={{ fontSize: 12 }}>
            <InfoCircleOutlined style={{ marginRight: 4 }} />
            Din virksomhed har skævt regnskabsår (starter i måned {activeCompany.fiscalYearStart}).
            Datoerne er automatisk justeret baseret på dette.
          </Text>
        </>
      )}
    </Modal>
  );
}
