import { useState, useEffect } from 'react';
import {
  Button,
  Form,
  Input,
  Modal,
  Popconfirm,
  Popover,
  Space,
  Spin,
  Table,
  message,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { AppContainer } from '../../../components/AppContainer';
import jwtAxios from '../../../api/axiosInstance';
import { ENDPOINTS } from '../../../api/endpoints';

const ENTITY_LABEL = 'UPI'; // e.g. 'UPI'
const ENTITY_ENDPOINT = ENDPOINTS.SETTINGS_UPI; // /api/upis


interface DataRecord {
  key: number;
  id: string;
  upiId: string;
}

const UPI = () => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  // null = "Add" mode. Holds the record's id while editing.
  const [editingId, setEditingId] = useState<string | null>(null);
  const [data, setData] = useState<DataRecord[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setOpen(true);
  };

  // Edit button click — GET the single record by id, then populate the
  // same form/modal used for "Add". We just switch modes with editingId.
  const handleEdit = async (id: string) => {
    setLoading(true);
    try {
      const res = await jwtAxios.get(`${ENTITY_ENDPOINT}/${id}`);
      // Adjust this line if your single-record response is wrapped
      // differently (e.g. res.data.result.data instead of res.data.result).
      const record = res.data?.result ?? res.data;

      form.setFieldsValue({
        upiId: record.upiId,
      });

      setEditingId(id);
      setOpen(true);
    } catch (err: any) {
      message.error(err.response?.data?.message || `Failed to load ${ENTITY_LABEL}`);
    } finally {
      setLoading(false);
    }
  };

  // -----------------------------
  // Fetch all UPIs — no pagination or search since there are at most 2.
  // -----------------------------
  const fetchData = async () => {
    setLoading(true);

    try {
      const res = await jwtAxios.get(ENTITY_ENDPOINT);
      // message.success(res?.data?.message);
      // Response shape: { message, result: [ { id, upiId }, ... ] }
      const records = res.data?.result || [];

      const formattedData = records.map((item: any) => ({
        key: item.id,
        ...item,
      }));

      setData(formattedData);
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch data');
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // Delete — actual API call happens only after the user confirms
  // in the Popconfirm popup (see the Actions column below).
  const handleDelete = async (id: string) => {
    setLoading(true);
    try {
      const res = await jwtAxios.delete(`${ENTITY_ENDPOINT}/${id}`);
      message.success(res.data?.message || `${ENTITY_LABEL} deleted successfully`);
      fetchData();
    } catch (err: any) {
      message.error(err.response?.data?.message || `Failed to delete ${ENTITY_LABEL}`);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);

    try {
      const payload = { upiId: values.upiId };

      const response = editingId
        ? await jwtAxios.put(`${ENTITY_ENDPOINT}/${editingId}`, payload)
        : await jwtAxios.post(ENTITY_ENDPOINT, payload);

      message.success(
        response.data?.message || `${ENTITY_LABEL} ${editingId ? 'updated' : 'added'} successfully`
      );
      setOpen(false);
      setEditingId(null);
      form.resetFields();
      fetchData();
    } catch (err: any) {
      const responseData = err.response?.data;
      const fieldErrors = responseData?.errors;

      if (fieldErrors && typeof fieldErrors === 'object') {
        // Map { upiId: "Invalid UPI ID format", ... } onto the matching
        // Form.Item so the error shows right under that field.
        form.setFields(
          Object.entries(fieldErrors).map(([name, error]) => ({
            name,
            errors: [String(error)],
          }))
        );
        message.error(responseData?.message || 'Please fix the highlighted fields');
      } else {
        // Covers the "already have 2 records" rejection too, since that's
        // a top-level message rather than a field-specific error.
        message.error(
          responseData?.message || `Failed to ${editingId ? 'update' : 'add'} ${ENTITY_LABEL}`
        );
      }
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: 'UPI ID',
      dataIndex: 'upiId',
    },
    {
      title: 'Actions',
      render: (_: any, record: any) => (
        <Space>
          <Popover content={<>Edit</>}>
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record.id)} />
          </Popover>
          <Popconfirm
            title={`Delete ${ENTITY_LABEL}`}
            description={`Are you sure you want to delete "${record.upiId}"?`}
            okText="Delete"
            cancelText="Cancel"
            okButtonProps={{ danger: true }}
            onConfirm={() => handleDelete(record.id)} // API call fires only after confirm
          >
            <Popover content={<>Delete</>}>
              <Button danger type="link" icon={<DeleteOutlined />} />
            </Popover>
          </Popconfirm>
        </Space>
      ),
    },
  ];


  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title="UPI Settings"
          headerAction={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
              className="bg-green-600"
            >
              Add
            </Button>
          }
        >
          {/* Table Section — no search or pagination, at most 2 rows */}
          <Table
            rowKey="key"
            columns={columns}
            dataSource={data}
            loading={loading}
            pagination={false}
          />
        </AppContainer>

        <Modal
          title={editingId ? `Edit ${ENTITY_LABEL}` : `Add ${ENTITY_LABEL}`}
          open={open}
          onCancel={() => {
            setOpen(false);
            setEditingId(null);
          }}
          onOk={() => form.submit()}
          confirmLoading={loading}
          okText="Submit"
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              label="UPI ID"
              name="upiId"
              rules={[
                { required: true },
                {
                  pattern: /^[\w.\-]{2,256}@[a-zA-Z][\w]{2,64}$/,
                  message: 'Enter a valid UPI ID (e.g. name@bank)',
                },
              ]}
            >
              <Input placeholder="example@upi" />
            </Form.Item>
          </Form>
        </Modal>
      </Spin>
    </div>
  );
};

export default UPI;