'use client';
import React, { useEffect, useState } from 'react';
import { Modal, Upload, Button, Alert, Table, Typography, Space, notification } from 'antd';
import type { UploadFile } from 'antd';
import { DownloadOutlined, InboxOutlined } from '@ant-design/icons';
import { importWhatsAppPhoneNumbers } from './service';

const { Text } = Typography;
const { Dragger } = Upload;

const ALLOWED_EXTENSIONS = ['.csv', '.xlsx', '.xls'];
const MAX_FILE_SIZE_MB = 5;
const MAX_ROWS = 50;

// Sample ("model") file columns. Keep these in sync with the backend import.
const SAMPLE_HEADERS = ['Country Code', 'Phone Number', 'Verified Name'];
const SAMPLE_ROWS = [
  ['91', '9876543210', 'Housiey Assist'],
  ['91', '9876543211', 'Housiey Assist 2'],
];

interface ImportPhoneNumbersModalProps {
  open: boolean;
  onClose: () => void;
  onImported: () => void;
}

interface FailedRow {
  key: string;
  row: string;
  field: string;
  message: string;
}

const downloadSampleFile = (): void => {
  const csv = [SAMPLE_HEADERS, ...SAMPLE_ROWS].map((line) => line.join(',')).join('\r\n');
  // BOM so Excel opens the UTF-8 CSV correctly
  const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'whatsapp-phone-numbers-sample.csv';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

const ImportPhoneNumbersModal: React.FC<ImportPhoneNumbersModalProps> = ({ open, onClose, onImported }) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [failedRows, setFailedRows] = useState<FailedRow[]>([]);
  const [summary, setSummary] = useState<{ type: 'success' | 'warning'; text: string } | null>(null);

  useEffect(() => {
    if (open) {
      setFileList([]);
      setFailedRows([]);
      setSummary(null);
    }
  }, [open]);

  const beforeUpload = (file: File): boolean => {
    const lowerName = file.name.toLowerCase();
    if (!ALLOWED_EXTENSIONS.some((ext) => lowerName.endsWith(ext))) {
      notification.error({
        message: 'Invalid file',
        description: 'Please select a .csv, .xlsx or .xls file. Download the sample file for the format.',
      });
      return Upload.LIST_IGNORE as unknown as boolean;
    }
    if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
      notification.error({
        message: 'File too large',
        description: `The file must be smaller than ${MAX_FILE_SIZE_MB} MB.`,
      });
      return Upload.LIST_IGNORE as unknown as boolean;
    }
    setFailedRows([]);
    setSummary(null);
    setFileList([file as unknown as UploadFile]);
    // Returning false keeps antd from uploading automatically; we submit on "Import"
    return false;
  };

  const handleImport = async (): Promise<void> => {
    const file = fileList[0] as unknown as File | undefined;
    if (!file) {
      notification.error({ message: 'Please select a file to import.' });
      return;
    }

    setLoading(true);
    setFailedRows([]);
    setSummary(null);
    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await importWhatsAppPhoneNumbers(formData);
      const result = response?.data ?? response;

      // Failed rows are reported like the lead import: { "<row>": { "<column>": "<message>" } }
      const failed = result?.failedRow as Record<string, Record<string, string>> | undefined;
      const formattedFailed: FailedRow[] = [];
      if (failed && typeof failed === 'object') {
        Object.entries(failed).forEach(([row, errors]) => {
          Object.entries(errors || {}).forEach(([field, message]) => {
            formattedFailed.push({ key: `${row}-${field}`, row, field, message: String(message) });
          });
        });
      }
      setFailedRows(formattedFailed);

      const message = result?.message || 'Phone numbers imported successfully.';
      if (formattedFailed.length > 0) {
        setSummary({ type: 'warning', text: `${message} Fix the rows below and import again.` });
        // Valid rows (if any) were registered, so refresh the list behind the modal
        if (result?.successRow?.length > 0) onImported();
      } else {
        notification.success({ message: 'Success', description: message });
        onImported();
        onClose();
      }
    } catch (error: any) {
      notification.error({
        message: 'Import failed',
        description: error?.response?.data?.message || 'Failed to import phone numbers.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      title="Import Phone Numbers"
      onCancel={loading ? undefined : onClose}
      maskClosable={!loading}
      destroyOnClose
      width={640}
      footer={[
        <Button key="cancel" onClick={onClose} disabled={loading}>
          Cancel
        </Button>,
        <Button
          key="import"
          type="primary"
          onClick={handleImport}
          loading={loading}
          disabled={fileList.length === 0}>
          Import
        </Button>,
      ]}>
      <Space direction="vertical" size={16} style={{ width: '100%' }}>
        <div>
          <Text>
            Add the country code, phone number and verified name of each number to the sample file, then upload it to
            register them with your WhatsApp Business Account.
          </Text>
          <div style={{ marginTop: 8 }}>
            <Button icon={<DownloadOutlined />} onClick={downloadSampleFile}>
              Download sample file
            </Button>
          </div>
        </div>

        <Alert
          type="info"
          showIcon
          message="File format"
          description={
            <ul style={{ margin: 0, paddingLeft: 18 }}>
              <li><b>Country Code</b>: digits only, for example 91</li>
              <li><b>Phone Number</b>: without the country code (10 digits for India)</li>
              <li><b>Verified Name</b>: the display name shown on WhatsApp</li>
              <li>
                Format the Country Code and Phone Number columns as <b>Text</b> in Excel, otherwise long numbers may be
                saved in scientific notation.
              </li>
              <li>Up to {MAX_ROWS} numbers per file.</li>
            </ul>
          }
        />

        <Alert
          type="warning"
          showIcon
          message="What the import does"
          description="Each number is only registered with the WhatsApp Business Account, with the default Housiey description and the PROF_SERVICES category. No verification code is sent - verify and generate the PIN for each number afterwards."
        />

        <Dragger
          accept={ALLOWED_EXTENSIONS.join(',')}
          multiple={false}
          maxCount={1}
          fileList={fileList}
          beforeUpload={beforeUpload}
          onRemove={() => {
            setFileList([]);
            setFailedRows([]);
            setSummary(null);
          }}
          disabled={loading}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">Click or drag a file here</p>
          <p className="ant-upload-hint">.csv, .xlsx or .xls, up to {MAX_FILE_SIZE_MB} MB</p>
        </Dragger>

        {summary && <Alert type={summary.type} showIcon message={summary.text} />}

        {failedRows.length > 0 && (
          <Table
            size="small"
            bordered
            pagination={{ pageSize: 5, hideOnSinglePage: true }}
            dataSource={failedRows}
            columns={[
              { title: 'Row', dataIndex: 'row', key: 'row', width: 80 },
              { title: 'Field', dataIndex: 'field', key: 'field', width: 160 },
              { title: 'Error', dataIndex: 'message', key: 'message' },
            ]}
          />
        )}
      </Space>
    </Modal>
  );
};

export default ImportPhoneNumbersModal;
