'use client';
import React, { useEffect, useState, useRef } from 'react';
import { Button, Table, Space, Popconfirm, notification, Tag, Select, Input } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, EyeInvisibleOutlined, UploadOutlined } from '@ant-design/icons';
import { getSipCredentials, deleteSipCredential } from './service';
import type { SipCredential, Filters } from './interface';
import ModalBox from './component/modal';
import ImportSipModal from './component/ImportSipModal';
import PageHeader from '@/components/pageHeader';
import { TablePaginationConfig } from 'antd/lib';
import { useDebounce } from 'use-debounce';

const SipCredentialsList: React.FC = () => {
  const [data, setData] = useState<SipCredential[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [editValue, setEditValue] = useState<SipCredential | null>(null);

  // Track which rows have password visible
  const [visiblePasswords, setVisiblePasswords] = useState<Record<number, boolean>>({});

  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearch] = useDebounce(searchTerm, 500);
  const isFirstMount = useRef(true);

  const [filters, setFilters] = useState<Filters>({
    page: 1,
    limit: 10,
    search: '',
    allocated: undefined,
  });

  // Fetch SIP credentials
  const fetchCredentials = (currentFilters: Filters): void => {
    setLoading(true);
    getSipCredentials(currentFilters)
      .then((response) => {
        const result = response?.data || {};
        setData(result.data || []);
        setTotal(result.meta?.total || 0);
      })
      .catch((error) => {
        const { message } = error?.response?.data || {};
        notification.error({
          message: 'Error',
          description: message || 'Failed to fetch SIP credentials.',
        });
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    fetchCredentials(filters);
  }, [filters]);

  useEffect(() => {
    if (isFirstMount.current) {
      isFirstMount.current = false;
      return;
    }
    setFilters((prev) => ({
      ...prev,
      page: 1,
      search: debouncedSearch,
    }));
  }, [debouncedSearch]);

  const handleCloseModal = (): void => {
    setIsModalOpen(false);
    setEditValue(null);
  };

  const handleEdit = (record: SipCredential): void => {
    setEditValue(record);
    setIsModalOpen(true);
  };

  const handleDelete = (id: number): void => {
    deleteSipCredential(id)
      .then((response) => {
        notification.success({
          message: 'Success',
          description: response?.data?.message || 'SIP credential deleted successfully.',
        });
        fetchCredentials(filters);
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error?.response?.data?.message || 'Failed to delete SIP credential.',
        });
      });
  };

  const handleAddCredential = (): void => {
    setIsModalOpen(true);
    setEditValue(null);
  };

  const handleOk = (): void => {
    fetchCredentials(filters);
    setIsModalOpen(false);
  };

  const onTableChange = (pagination: TablePaginationConfig): void => {
    setFilters((prev) => ({
      ...prev,
      page: pagination.current,
      limit: pagination.pageSize,
    }));
  };

  const togglePasswordVisibility = (id: number) => {
    setVisiblePasswords((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  const columns: ColumnsType<SipCredential> = [
    {
      title: 'Username',
      dataIndex: 'username',
      key: 'username',
      width: 140,
      sorter: (a, b) => a.username.localeCompare(b.username),
    },
    {
      title: 'Password',
      dataIndex: 'password',
      key: 'password',
      width: 220,
      render: (_, record) => {
        const isVisible = visiblePasswords[record.id];
        return (
          <Space>
            <span>{isVisible ? record.password : '••••••••'}</span>
            <Button
              type="text"
              icon={isVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
              onClick={() => togglePasswordVisibility(record.id)}
              size="small"
            />
          </Space>
        );
      },
    },
    {
      title: 'DID Number',
      dataIndex: 'did_number',
      key: 'did_number',
      width: 140,
      render: (did) => did || <span style={{ color: '#bfbfbf' }}>N/A</span>,
    },
    {
      title: 'Office Number',
      dataIndex: 'office_assigned_number',
      key: 'office_assigned_number',
      width: 160,
      render: (num) => num || <span style={{ color: '#bfbfbf' }}>N/A</span>,
    },
    {
      title: 'Allocated',
      dataIndex: 'allocated',
      key: 'allocated',
      width: 110,
      render: (allocated: boolean) => (
        <Tag color={allocated ? 'green' : 'red'}>
          {allocated ? 'Yes' : 'No'}
        </Tag>
      ),
    },

    {
      title: 'Created At',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: 'Action',
      key: 'action',
      className: 'w-1 nowrap',
      align: 'center',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            size="middle"
            title="Edit"
            onClick={() => handleEdit(record)}
          />
          <Popconfirm
            title={
              record.allocated
                ? "This DID number is currently allocated to an employee. Deleting this credential will remove the DID number association from the employee. Are you sure you want to delete this record?"
                : "Are you sure you want to delete this SIP credential?"
            }
            onConfirm={() => handleDelete(record.id)}
            okText="Yes"
            cancelText="No"
            placement="topRight">
            <Button
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
              size="middle"
              title="Delete"
              danger
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <PageHeader
        title="Manage SIP Credentials"
        isBack={false}
        extra={
          <Space size="middle" align="center">
            <Input
              placeholder="Search by Username/DID"
              allowClear
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              style={{ width: 220, marginLeft: 10 }}
            />
            <Select
              placeholder="Filter allocation"
              allowClear
              style={{ width: 170 }}
              onChange={(value) => {
                setFilters((prev) => ({
                  ...prev,
                  page: 1,
                  allocated: value,
                }));
              }}
              options={[
                { value: 'true', label: 'Allocated (Yes)' },
                { value: 'false', label: 'Not Allocated (No)' },
              ]}
            />

            <Button
              type="primary"
              onClick={() => setIsImportModalOpen(true)}>
              Import
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddCredential}>
              Add SIP Credential
            </Button>
          </Space>
        }
      />

      <div style={{ marginTop: 16 }}>
        <Table
          loading={loading}
          rowKey="id"
          columns={columns}
          bordered
          dataSource={data}
          onChange={onTableChange}
          pagination={{
            pageSize: filters.limit,
            current: filters.page,
            total: total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            defaultPageSize: 10,
            showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} entries`,
          }}
        />
      </div>

      <ImportSipModal
        open={isImportModalOpen}
        onClose={() => setIsImportModalOpen(false)}
        onImported={() => fetchCredentials(filters)}
      />

      <ModalBox
        isModalOpen={isModalOpen}
        data={editValue}
        handleOk={handleOk}
        handleClose={handleCloseModal}
      />
    </div>
  );
};

export default SipCredentialsList;
