import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Result, Button, Input, App, Space } from 'antd';
import { ArrowLeftOutlined, HomeOutlined, MailOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth.store';
import { isAdmin } from '@/utils/roles';

const API_URL = import.meta.env.VITE_API_URL || '';

export default function NotFoundPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { message } = App.useApp();
  const { user, isAuthenticated } = useAuthStore();

  const [reporting, setReporting] = useState(false);
  const [showInput, setShowInput] = useState(false);
  const [reportMessage, setReportMessage] = useState('');

  const homePath = !isAuthenticated
    ? '/home'
    : user && isAdmin(user)
      ? '/app'
      : '/volunteer';

  const handleReport = async () => {
    if (!showInput) {
      setShowInput(true);
      return;
    }

    setReporting(true);
    try {
      await axios.post(`${API_URL}/api/public/error-report`, {
        url: location.pathname + location.search,
        message: reportMessage || undefined,
        userAgent: navigator.userAgent,
      });
      message.success('Report sent to admins. Thank you!');
      setShowInput(false);
      setReportMessage('');
    } catch {
      message.error('Failed to send report. Please try again later.');
    } finally {
      setReporting(false);
    }
  };

  return (
    <Result
      status="404"
      title="404"
      subTitle={`The page "${location.pathname}" was not found.`}
      extra={
        <Space direction="vertical" size="middle" style={{ width: '100%', maxWidth: 400 }}>
          <Space wrap>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>
              Go Back
            </Button>
            <Button type="primary" icon={<HomeOutlined />} onClick={() => navigate(homePath)}>
              Go Home
            </Button>
            <Button
              icon={<MailOutlined />}
              onClick={handleReport}
              loading={reporting}
            >
              Report to Admin
            </Button>
          </Space>
          {showInput && (
            <div>
              <Input.TextArea
                placeholder="Optional: describe what you were looking for..."
                value={reportMessage}
                onChange={(e) => setReportMessage(e.target.value)}
                rows={3}
                maxLength={500}
                showCount
                style={{ marginBottom: 8 }}
              />
              <Button type="primary" onClick={handleReport} loading={reporting} block>
                Send Report
              </Button>
            </div>
          )}
        </Space>
      }
    />
  );
}
