'use client';

import React, { useEffect, useState, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useDebounce } from 'use-debounce';
import {
  Table,
  Input,
  Select,
  Button,
  Space,
  Tag,
  Typography,
  Card,
  Avatar,
  Drawer,
  notification,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  SettingOutlined,
  WhatsAppOutlined,
  SafetyCertificateOutlined,
  KeyOutlined,
  LockOutlined,
  PlusOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { AppDispatch, RootState } from '@/store/store';
import { fetchWhatsAppPhoneNumbers, syncWhatsAppPhoneNumbersThunk } from './slice';
import type { WhatsAppPhoneNumber } from './interface';
import AddPhoneNumberModal from './AddPhoneNumberModal';
import ImportPhoneNumbersModal from './ImportPhoneNumbersModal';
import GeneratePinModal from './GeneratePinModal';
import ChangePinModal from './ChangePinModal';
import DeregisterPhoneNumberModal from './DeregisterPhoneNumberModal';
import { updatePhoneNumberProfile } from './service';

const { Text, Title } = Typography;
const { TextArea } = Input;

export default function PhoneNumbersPage() {
  const dispatch: AppDispatch = useDispatch();
  const { phoneNumbers, status, total, statuses } = useSelector((state: RootState) => state.phoneNumbers);

  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText] = useDebounce(searchText, 400);
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  // '' = all, 'true' = allocated to a user, 'false' = not allocated
  const [selectedAllocated, setSelectedAllocated] = useState<string>('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10); // default records per page
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);

  // Verify OTP modal state (verifyOnly mode)
  const [verifyModalOpen, setVerifyModalOpen] = useState(false);
  const [verifyPhoneRecord, setVerifyPhoneRecord] = useState<WhatsAppPhoneNumber | null>(null);

  // Generate PIN modal state (PENDING numbers)
  const [pinRecord, setPinRecord] = useState<WhatsAppPhoneNumber | null>(null);
  const openPinModal = (record: WhatsAppPhoneNumber) => setPinRecord(record);

  // Change PIN modal state
  const [changePinRecord, setChangePinRecord] = useState<WhatsAppPhoneNumber | null>(null);

  // Deregister modal state (delete icon)
  const [deregisterRecord, setDeregisterRecord] = useState<WhatsAppPhoneNumber | null>(null);

  // Settings drawer state
  const [settingsDrawerOpen, setSettingsDrawerOpen] = useState(false);
  const [settingsRecord, setSettingsRecord] = useState<WhatsAppPhoneNumber | null>(null);
  const [editDisplayName, setEditDisplayName] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [savingProfile, setSavingProfile] = useState(false);

  // An emptied search box applies at once instead of waiting for the debounce (a stale term would fire a request)
  const effectiveSearch = searchText.trim() === '' ? '' : debouncedSearchText.trim();

  // Filters and paging are applied by the API; reload whenever one of them changes
  useEffect(() => {
    dispatch(
      fetchWhatsAppPhoneNumbers({
        page,
        pageSize,
        allocated: selectedAllocated,
        status: selectedStatus,
        search: effectiveSearch,
      })
    );
  }, [dispatch, page, pageSize, selectedAllocated, selectedStatus, effectiveSearch]);

  // Reload with the current filters/page after an action (add, verify, PIN, profile, import)
  const reloadList = () => dispatch(fetchWhatsAppPhoneNumbers({ refresh: true }));

  // Pull the numbers from the WhatsApp Cloud API into our DB; the response carries the refreshed DB list
  const [syncing, setSyncing] = useState(false);
  const handleSync = async () => {
    setSyncing(true);
    try {
      // After a sync show everything that was updated: first page, no filters
      const result: any = await dispatch(
        syncWhatsAppPhoneNumbersThunk({ page: 1, pageSize, allocated: '', status: '', search: '' })
      ).unwrap();
      setSearchText('');
      setSelectedStatus('');
      setSelectedAllocated('');
      setPage(1);
      const body = result?.response?.data;
      const s = body?.summary;
      notification.success({
        message: 'Synced with WhatsApp',
        description: s
          ? `${s.added} added, ${s.updated} updated, ${s.unchanged} unchanged` +
            (s.failed ? `, ${s.failed} failed` : '') +
            (s.not_in_whatsapp ? `. ${s.not_in_whatsapp} saved number(s) are not in the WhatsApp account.` : '.')
          : body?.message,
      });
    } catch (error: any) {
      notification.error({
        message: 'Sync failed',
        description:
          error?.response?.data?.message || error?.message || 'Could not sync with WhatsApp. Please try again.',
      });
    } finally {
      setSyncing(false);
    }
  };

  // 👉 Temporary: log actual status values to help debug the Verify button
  useEffect(() => {
    if (phoneNumbers?.length) {
      console.log('[PhoneNumbers] status values:', phoneNumbers.map((p) => ({
        display_phone_number: p.display_phone_number,
        status: p.status,
        code_verification_status: p.code_verification_status,
      })));
    }
  }, [phoneNumbers]);

  // Save profile changes
  const handleSaveProfile = async () => {
    if (!settingsRecord?.id) return;
    setSavingProfile(true);
    try {
      await updatePhoneNumberProfile({
        phone_number_id: settingsRecord.id,
        verified_name: editDisplayName.trim() || undefined,
        description: editDescription.trim() || undefined,
      });
      notification.success({
        message: 'Profile updated',
        description: 'Phone number profile has been updated successfully.',
      });
      reloadList();
      setSettingsDrawerOpen(false);
    } catch (error: any) {
      notification.error({
        message: 'Update failed',
        description:
          error?.response?.data?.message || 'Failed to update profile. Please try again.',
      });
    } finally {
      setSavingProfile(false);
    }
  };

  // Open settings drawer
  const openSettingsDrawer = (record: WhatsAppPhoneNumber) => {
    setSettingsRecord(record);
    setEditDisplayName(record.verified_name || '');
    setEditDescription('');
    setSettingsDrawerOpen(true);
  };

  // Open verify modal for NOT_VERIFIED numbers
  const openVerifyModal = (record: WhatsAppPhoneNumber) => {
    setVerifyPhoneRecord(record);
    setVerifyModalOpen(true);
  };

  // Statuses come from the API (every status in the account), so the dropdown doesn't shrink to the current page
  const statusOptions = useMemo(
    () => [
      { value: '', label: 'Filter by status' },
      ...(statuses || []).map((st) => ({ value: st, label: st })),
    ],
    [statuses]
  );

  const columns: ColumnsType<WhatsAppPhoneNumber> = [
    {
      title: 'Phone number',
      dataIndex: 'display_phone_number',
      key: 'display_phone_number',
      render: (text, record) => {
        const verificationStatus = record.code_verification_status?.toUpperCase();
        // A CONNECTED number is registered on the Cloud API, so it is already verified: never ask to verify it
        const isNotVerified =
          record.status?.toUpperCase() !== 'CONNECTED' &&
          verificationStatus !== 'VERIFIED' &&
          (record.status?.toUpperCase() === 'PENDING' ||
            verificationStatus === 'NOT_VERIFIED' ||
            verificationStatus === 'UNVERIFIED' ||
            verificationStatus?.includes('NOT_VERIF'));
        // OTP verification done but no PIN registered yet: Generate PIN replaces Verify
        const canGeneratePin =
          verificationStatus === 'VERIFIED' &&
          record.status?.toUpperCase() === 'PENDING' &&
          !record.has_pin;

        return (
          <Space align="start">
            <Avatar
              icon={<WhatsAppOutlined />}
              style={{ backgroundColor: '#25D366', color: 'white', marginTop: 4 }}
              size="small"
            />
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <Text strong>{text || '-'}</Text>
              {isNotVerified ? (
                <Button
                  size="small"
                  type="primary"
                  icon={<SafetyCertificateOutlined />}
                  onClick={() => openVerifyModal(record)}
                  style={{ borderRadius: 6, marginTop: 4, width: 'fit-content' }}
                >
                  Verify
                </Button>
              ) : canGeneratePin ? (
                <Button
                  size="small"
                  type="primary"
                  icon={<KeyOutlined />}
                  onClick={() => openPinModal(record)}
                  style={{ borderRadius: 6, marginTop: 4, width: 'fit-content' }}
                >
                  Generate PIN
                </Button>
              ) : (
                record.code_verification_status && (
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {record.code_verification_status}
                  </Text>
                )
              )}
            </div>
          </Space>
        );
      },
    },
    {
      title: 'Name',
      dataIndex: 'verified_name',
      key: 'verified_name',
      render: (text) => (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <Text>{text || '-'}</Text>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            Name visible to customers
          </Text>
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (itemStatus: string) => {
        const upper = itemStatus?.toUpperCase();
        let color = 'default';
        if (['APPROVED', 'CONNECTED', 'VERIFIED'].includes(upper)) color = 'success';
        else if (upper === 'PENDING') color = 'warning';
        else if (['REJECTED', 'FAILED', 'RESTRICTED'].includes(upper)) color = 'error';

        return (
          <Tag color={color} style={{ borderRadius: '12px', padding: '0 8px' }}>
            {itemStatus || 'UNKNOWN'}
          </Tag>
        );
      },
    },
    {
      title: 'Allocated',
      dataIndex: 'allocated',
      key: 'allocated',
      render: (allocated: boolean) => (
        <Tag color={allocated ? 'success' : 'default'} style={{ borderRadius: '12px', padding: '0 8px' }}>
          {allocated ? 'Yes' : 'No'}
        </Tag>
      ),
    },
    {
      title: 'Quality rating',
      dataIndex: 'quality_rating',
      key: 'quality_rating',
      render: (rating?: string | null) => {
        const upperRating = rating?.toUpperCase();
        let dotColor = '#d9d9d9';
        let displayText = rating || '-';

        if (upperRating === 'GREEN' || upperRating === 'HIGH') {
          dotColor = '#52c41a';
          displayText = 'High';
        } else if (upperRating === 'YELLOW' || upperRating === 'MEDIUM') {
          dotColor = '#faad14';
          displayText = 'Medium';
        } else if (upperRating === 'RED' || upperRating === 'LOW') {
          dotColor = '#ff4d4f';
          displayText = 'Low';
        } else if (upperRating === 'UNKNOWN') {
          displayText = 'Unknown';
        }

        return (
          <Space>
            <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: dotColor }} />
            <Text>{displayText}</Text>
          </Space>
        );
      },
    },
    {
      title: '',
      key: 'actions',
      align: 'right',
      render: (_, record) => (
        <Space size="small">
          {record.has_pin && (
            <Button
              icon={<LockOutlined />}
              size="small"
              title="Change PIN"
              onClick={() => setChangePinRecord(record)}
            />
          )}
          {/* Only numbers with a PIN are registered on the Cloud API, so only they can be deregistered
              (deregistering clears the PIN, so a deregistered number loses the icon) */}
          {record.has_pin && (
            <Button
              icon={<DeleteOutlined />}
              size="small"
              title="Deregister"
              onClick={() => setDeregisterRecord(record)}
            />
          )}
          <Button
            icon={<SettingOutlined />}
            size="small"
            onClick={() => openSettingsDrawer(record)}
          />
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: 12,
          marginBottom: 24,
        }}
      >
        <Typography.Title level={4} style={{ margin: 0, fontWeight: 600 }}>
          Manage WhatsApp Numbers
        </Typography.Title>
        <Button
          icon={<SyncOutlined spin={syncing} />}
          disabled={syncing}
          style={{ borderRadius: 4, fontWeight: 500 }}
          title="Fetch the numbers from the WhatsApp Business Account and update this list"
          onClick={handleSync}
        >
          Sync WhatsApp numbers
        </Button>
      </div>
      <Card
        bordered={false}
        style={{ borderRadius: 8, boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)' }}
        bodyStyle={{ padding: 0 }}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '16px 24px',
            borderBottom: '1px solid #f0f0f0',
            flexWrap: 'wrap',
            gap: '16px',
          }}
        >
          <Input
            prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
            placeholder="Search by phone number or name"
            style={{ width: 300, borderRadius: 4 }}
            value={searchText}
            onChange={(e) => {
              setSearchText(e.target.value);
              setPage(1);
            }}
            allowClear
          />
          <Space size="middle" style={{ flexWrap: 'wrap' }}>
            <Select
              value={selectedStatus}
              onChange={(value) => {
                setSelectedStatus(value);
                setPage(1);
              }}
              style={{ width: 160 }}
              options={statusOptions}
            />
            <Select
              value={selectedAllocated}
              onChange={(value) => {
                setSelectedAllocated(value);
                setPage(1);
              }}
              style={{ width: 180 }}
              options={[
                { value: '', label: 'Filter by allocation' },
                { value: 'true', label: 'Allocated (Yes)' },
                { value: 'false', label: 'Not Allocated (No)' },
              ]}
            />
            <Button
              type="primary"
              style={{ borderRadius: 4, fontWeight: 500 }}
              onClick={() => setIsImportModalOpen(true)}
            >
              Import
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              style={{ borderRadius: 4, fontWeight: 500 }}
              onClick={() => setIsModalOpen(true)}
            >
              Add phone number
            </Button>
          </Space>
        </div>
        <Table
          columns={columns}
          dataSource={phoneNumbers}
          loading={status === 'loading'}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            pageSizeOptions: [2, 5, 10, 20],
            showTotal: (count) => `${count} phone number${count === 1 ? '' : 's'}`,
            onChange: (nextPage, nextPageSize) => {
              if (nextPageSize !== pageSize) {
                setPageSize(nextPageSize);
                setPage(1);
              } else {
                setPage(nextPage);
              }
            },
          }}
          rowKey={(record) => record.id || record.display_phone_number}
          style={{ width: '100%' }}
        />
      </Card>

      {/* Add phone number modal (full flow) */}
      <AddPhoneNumberModal
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
      />

      {/* Bulk import: registers the numbers with the WhatsApp Business Account */}
      <ImportPhoneNumbersModal
        open={isImportModalOpen}
        onClose={() => setIsImportModalOpen(false)}
        onImported={reloadList}
      />

      {/* Generate PIN modal — opened from the PENDING status row */}
      <GeneratePinModal
        open={!!pinRecord}
        record={pinRecord}
        onCancel={() => setPinRecord(null)}
        onSuccess={() => {
          setPinRecord(null);
          reloadList();
        }}
      />

      {/* Change PIN modal — opened from the lock icon in the last column */}
      <ChangePinModal
        open={!!changePinRecord}
        record={changePinRecord}
        onCancel={() => setChangePinRecord(null)}
        onSuccess={() => setChangePinRecord(null)}
      />

      {/* Deregister modal — opened from the delete icon; shows the limitations and calls the API on confirm */}
      <DeregisterPhoneNumberModal
        open={!!deregisterRecord}
        record={deregisterRecord}
        onCancel={() => setDeregisterRecord(null)}
        onSuccess={() => {
          setDeregisterRecord(null);
          reloadList();
        }}
      />

      {/* Verify-only modal — opened from NOT_VERIFIED Verify button */}
      {verifyPhoneRecord && (
        <AddPhoneNumberModal
          open={verifyModalOpen}
          onCancel={() => {
            setVerifyModalOpen(false);
            setVerifyPhoneRecord(null);
          }}
          verifyOnly
          phoneNumberIdProp={verifyPhoneRecord.id}
          initialCodeMethod="SMS"
        />
      )}

      {/* ── Settings Drawer ──────────────────────────────────────── */}
      <Drawer
        title={
          <div>
            <Title level={5} style={{ margin: 0 }}>
              Edit phone number settings
            </Title>
            {settingsRecord && (
              <Text type="secondary" style={{ fontSize: 13 }}>
                {settingsRecord.display_phone_number}
              </Text>
            )}
          </div>
        }
        width={420}
        placement="right"
        open={settingsDrawerOpen}
        onClose={() => setSettingsDrawerOpen(false)}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <Button onClick={() => setSettingsDrawerOpen(false)} disabled={savingProfile}>
              Cancel
            </Button>
            <Button
              type="primary"
              loading={savingProfile}
              onClick={handleSaveProfile}
              disabled={!editDisplayName.trim()}
            >
              Save changes
            </Button>
          </div>
        }
      >
        <div style={{ padding: '8px 0' }}>
          <div style={{ marginBottom: 24 }}>
            <Text strong style={{ display: 'block', marginBottom: 8 }}>
              Display name
            </Text>
            <Text type="secondary" style={{ display: 'block', fontSize: 12, marginBottom: 8 }}>
              This is the name visible to your customers on WhatsApp.
            </Text>
            <Input
              value={editDisplayName}
              onChange={(e) => setEditDisplayName(e.target.value)}
              size="large"
              placeholder="Enter display name"
            />
          </div>

          <div style={{ marginBottom: 24 }}>
            <Text strong style={{ display: 'block', marginBottom: 8 }}>
              Business description{' '}
              <Text type="secondary" style={{ fontWeight: 'normal' }}>
                · Optional
              </Text>
            </Text>
            <TextArea
              value={editDescription}
              onChange={(e) => setEditDescription(e.target.value)}
              placeholder="Tell people about your business"
              rows={4}
              maxLength={512}
              showCount
            />
          </div>
        </div>
      </Drawer>
    </div>
  );
}
