import { useState, useMemo, useEffect, useCallback } from 'react';
import { Form, Input, Button, Table, Typography, Alert, Row, Col, Card, Space, Grid, message } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { useApi } from '@/hooks/useApi';
import { SubmissionsService } from '@/services/submissions';
import { parseError } from '@/utils/errorHandler';

const { useBreakpoint } = Grid;

interface Submission {
  id: string;
  name?: string;
  email?: string;
  created_at: string;
  updated_at: string;
}

interface PaginatedResponse {
  items: Submission[];
  total: number;
  limit: number;
  offset: number;
}

const FormAndListPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const screens = useBreakpoint();

  const [searchTerm, setSearchTerm] = useState<string>('');
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(20);

  const { 
    data: submissionsData, 
    loading: isLoading, 
    error, 
    execute: fetchSubmissions 
  } = useApi<PaginatedResponse>(SubmissionsService.list);

  const loadSubmissions = useCallback(() => {
    const offset = (currentPage - 1) * pageSize;
    void fetchSubmissions({
      limit: pageSize,
      offset,
      ...(searchTerm ? { email: searchTerm } : {})
    });
  }, [fetchSubmissions, currentPage, pageSize, searchTerm]);

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

  useEffect(() => {
    if (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage);
    }
  }, [error, messageApi]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      await SubmissionsService.create({
        name: values.name,
        email: values.email
      });
      messageApi.success('Submission created successfully');
      form.resetFields();
      setCurrentPage(1);
      loadSubmissions();
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  };

  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const handleTableChange = (pagination: { current?: number; pageSize?: number }) => {
    if (pagination.current) {
      setCurrentPage(pagination.current);
    }
    if (pagination.pageSize) {
      setPageSize(pagination.pageSize);
      setCurrentPage(1);
    }
  };

  const columns = useMemo(() => [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      responsive: ['md'] as const,
      ellipsis: true
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text: string | undefined) => text ?? '—'
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      render: (text: string | undefined) => text ?? '—'
    },
    {
      title: 'Created',
      dataIndex: 'created_at',
      key: 'created_at',
      responsive: ['lg'] as const,
      render: (date: string) => new Date(date).toLocaleDateString()
    }
  ], []);

  const dataSource = useMemo(() => {
    return (submissionsData?.items ?? []);
  }, [submissionsData]);

  const padding = screens.xs ? 12 : 24;

  return (
    <div style={{ padding, minHeight: '100%', width: '100%' }}>
      {contextHolder}
      
      <Space direction="vertical" size={16} style={{ width: '100%' }}>
        <Typography.Title level={screens.xs ? 3 : 2}>
          Single Page Sample
        </Typography.Title>

        <Card 
          title="Submit Your Info" 
          style={{ width: '100%' }}
          bodyStyle={{ padding: screens.xs ? 16 : 24 }}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12}>
                <Form.Item
                  name="name"
                  label="Name"
                  rules={[
                    { required: true, message: 'Name is required' },
                    { min: 2, message: 'Name must be at least 2 characters' },
                    { max: 100, message: 'Name must not exceed 100 characters' }
                  ]}
                >
                  <Input 
                    placeholder="Enter your name" 
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              
              <Col xs={24} sm={12}>
                <Form.Item
                  name="email"
                  label="Email"
                  rules={[
                    { required: true, message: 'Email is required' },
                    { type: 'email', message: 'Please enter a valid email' },
                    { max: 255, message: 'Email must not exceed 255 characters' }
                  ]}
                >
                  <Input 
                    type="email"
                    placeholder="Enter your email" 
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>

              <Col xs={24}>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    icon={<PlusOutlined />}
                    block={screens.xs}
                    style={!screens.xs ? { float: 'right' } : undefined}
                  >
                    Submit
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card 
          title="Submissions" 
          style={{ width: '100%' }}
          bodyStyle={{ padding: screens.xs ? 8 : 24 }}
        >
          <Space direction="vertical" size={16} style={{ width: '100%' }}>
            <Input.Search
              placeholder="Search single page sample..."
              allowClear
              onSearch={handleSearch}
              onChange={(e) => {
                if (e.target.value === '') {
                  handleSearch('');
                }
              }}
              prefix={<SearchOutlined />}
              style={{ width: screens.xs ? '100%' : 300 }}
            />

            {error && (
              <Alert
                message="Error"
                description={parseError(error).message}
                type="error"
                showIcon
                closable
              />
            )}

            <Table
              rowKey="id"
              columns={columns}
              dataSource={dataSource}
              loading={isLoading}
              size={screens.xs ? 'small' : 'middle'}
              scroll={{ x: 'max-content' }}
              pagination={{
                current: currentPage,
                pageSize,
                total: submissionsData?.total ?? 0,
                showSizeChanger: true,
                showTotal: (total) => `Total ${total} items`,
                pageSizeOptions: ['10', '20', '50', '100']
              }}
              onChange={handleTableChange}
              locale={{
                emptyText: 'No submissions yet.'
              }}
            />
          </Space>
        </Card>
      </Space>
    </div>
  );
};

export default FormAndListPage;