import { useState, useEffect, useMemo, CSSProperties } from 'react';
import { Form, Input, Button, Card, Table, Typography, message } from 'antd';
import type { ColumnType } from 'antd/es/table';
import { useApi } from '@/hooks/useApi';
import { SubmissionsService } from '@/services/submissions';
import { useAppContext } from '@/store/AppStore';
import { parseError } from '@/utils/errorHandler';

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

const HomePage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const { submissions } = useAppContext();

  const [submitting, setSubmitting] = useState<boolean>(false);
  const [loadingSubmissions, setLoadingSubmissions] = useState<boolean>(true);

  const { data: fetchedSubmissions, loading: fetchLoading, error: fetchError, execute: fetchSubmissions } = useApi(SubmissionsService.list);

  useEffect(() => {
    void fetchSubmissions({ limit: 1000, offset: 0 });
  }, [fetchSubmissions]);

  useEffect(() => {
    if (!fetchLoading) {
      setLoadingSubmissions(false);
    }
  }, [fetchLoading]);

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

  const handleSubmit = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      
      await SubmissionsService.create({
        name: values.name,
        email: values.email
      });

      messageApi.success('Submission created successfully!');
      form.resetFields();
      
      await fetchSubmissions({ limit: 1000, offset: 0 });
      
      const nameInput = document.querySelector('input[id="submission_form_name"]') as HTMLInputElement;
      if (nameInput) {
        nameInput.focus();
      }
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Failed to create submission. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const formatDateTime = (dateString: string): string => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const columns = useMemo<ColumnType<Submission>[]>(() => [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 280,
      ellipsis: true
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: 'Created At',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => formatDateTime(text),
      sorter: (a: Submission, b: Submission) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
      defaultSortOrder: 'descend'
    }
  ], []);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    width: '100%',
    padding: '24px',
    backgroundColor: '#f5f5f5',
    display: 'flex',
    flexDirection: 'column'
  };

  const contentWrapperStyle: CSSProperties = {
    maxWidth: '900px',
    margin: '0 auto',
    width: '100%',
    display: 'flex',
    flexDirection: 'column'
  };

  const pageTitleStyle: CSSProperties = {
    marginBottom: '24px'
  };

  const formCardStyle: CSSProperties = {
    marginBottom: '24px'
  };

  const dataSource = submissions || fetchedSubmissions?.data || [];

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <div style={contentWrapperStyle}>
        <Typography.Title level={2} style={pageTitleStyle}>
          Todo Task Submissions
        </Typography.Title>

        <Card title="New Submission" style={formCardStyle}>
          <Form
            form={form}
            layout="vertical"
            name="submission_form"
            autoComplete="off"
            onFinish={handleSubmit}
          >
            <Form.Item
              label="Name"
              name="name"
              rules={[
                { required: true, message: 'Please enter your name' },
                { max: 100, message: 'Name must be at most 100 characters' }
              ]}
            >
              <Input
                placeholder="Enter your name"
                maxLength={100}
                allowClear
              />
            </Form.Item>

            <Form.Item
              label="Email"
              name="email"
              rules={[
                { required: true, message: 'Please enter your email' },
                { type: 'email', message: 'Please enter a valid email address' },
                { max: 255, message: 'Email must be at most 255 characters' }
              ]}
            >
              <Input
                placeholder="Enter your email"
                maxLength={255}
                allowClear
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={submitting}
              >
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Card>

        <Card title="Submissions">
          <Table<Submission>
            rowKey="id"
            dataSource={dataSource}
            columns={columns}
            loading={loadingSubmissions}
            pagination={{ pageSize: 20 }}
            locale={{
              emptyText: 'No submissions yet. Submit the form above to get started.'
            }}
          />
        </Card>
      </div>
    </div>
  );
};

export default HomePage;