"use client";

import { useState, useEffect } from 'react';
import { addDays, format } from 'date-fns';
import { DateRangePicker } from '@/app/components/ui/DateRangePicker';
import { Event } from '@/app/api/types';

export default function EventsPage() {
  const [dateRange, setDateRange] = useState({
    from: new Date('2024-02-01'),
    to: new Date('2025-03-05')
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [events, setEvents] = useState<Event[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [filter, setFilter] = useState({
    eventType: '',
    linkId: '',
    linkSlug: ''
  });

  const [filters, setFilters] = useState({
    startTime: format(new Date('2024-02-01'), "yyyy-MM-dd'T'HH:mm:ss'Z'"),
    endTime: format(new Date('2025-03-05'), "yyyy-MM-dd'T'HH:mm:ss'Z'"),
    page: 1,
    pageSize: 20
  });

  const [summary, setSummary] = useState<any>(null);

  const fetchEvents = async (pageNum: number) => {
    try {
      const startTime = format(dateRange.from, "yyyy-MM-dd'T'HH:mm:ss'Z'");
      const endTime = format(dateRange.to, "yyyy-MM-dd'T'HH:mm:ss'Z'");

      const params = new URLSearchParams({
        startTime,
        endTime,
        page: pageNum.toString(),
        pageSize: '50'
      });

      if (filter.eventType) params.append('eventType', filter.eventType);
      if (filter.linkId) params.append('linkId', filter.linkId);
      if (filter.linkSlug) params.append('linkSlug', filter.linkSlug);

      const response = await fetch(`/api/events?${params.toString()}`);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to fetch events');
      }

      const eventsData = data.data || data.events || [];
      
      if (pageNum === 1) {
        setEvents(eventsData);
      } else {
        setEvents(prev => [...prev, ...eventsData]);
      }

      setHasMore(Array.isArray(eventsData) && eventsData.length === 50);
    } catch (err) {
      console.error("Error fetching events:", err);
      setError(err instanceof Error ? err.message : 'An error occurred while fetching events');
      setEvents([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setPage(1);
    setEvents([]);
    setLoading(true);
    fetchEvents(1);
  }, [dateRange, filter]);

  const loadMore = () => {
    if (!loading && hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      fetchEvents(nextPage);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString();
  };

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-red-500">{error}</div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Events</h1>
        <DateRangePicker
          value={dateRange}
          onChange={setDateRange}
        />
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-500 dark:text-gray-400 mb-1">
              Event Type
            </label>
            <select
              value={filter.eventType}
              onChange={e => setFilter(prev => ({ ...prev, eventType: e.target.value }))}
              className="block w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md text-sm text-gray-900 dark:text-gray-100"
            >
              <option value="">All Types</option>
              <option value="click">Click</option>
              <option value="conversion">Conversion</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-500 dark:text-gray-400 mb-1">
              Link ID
            </label>
            <input
              type="text"
              value={filter.linkId}
              onChange={e => setFilter(prev => ({ ...prev, linkId: e.target.value }))}
              placeholder="Enter Link ID"
              className="block w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md text-sm text-gray-900 dark:text-gray-100"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-500 dark:text-gray-400 mb-1">
              Link Slug
            </label>
            <input
              type="text"
              value={filter.linkSlug}
              onChange={e => setFilter(prev => ({ ...prev, linkSlug: e.target.value }))}
              placeholder="Enter Link Slug"
              className="block w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md text-sm text-gray-900 dark:text-gray-100"
            />
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead className="bg-gray-50 dark:bg-gray-900">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Time
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Type
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Link
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Visitor
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Location
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Referrer
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Conversion
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {Array.isArray(events) && events.map((event, index) => (
                <tr key={event.event_id || index} className={index % 2 === 0 ? 'bg-white dark:bg-gray-800' : 'bg-gray-50 dark:bg-gray-900'}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    {event.event_time && formatDate(event.event_time)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      event.event_type === 'conversion' ? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100' : 'bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-100'
                    }`}>
                      {event.event_type || 'unknown'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    <div>
                      <div className="font-medium">{event.link_slug || '-'}</div>
                      <div className="text-gray-500 dark:text-gray-400 text-xs">{event.link_original_url || '-'}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    <div>
                      <div>{event.browser || '-'}</div>
                      <div className="text-gray-500 dark:text-gray-400 text-xs">{event.os || '-'} / {event.device_type || '-'}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    <div>
                      <div>{event.city || '-'}</div>
                      <div className="text-gray-500 dark:text-gray-400 text-xs">{event.country || '-'}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                    {event.referrer || '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    <div>
                      <div>{event.conversion_type || '-'}</div>
                      {event.conversion_value > 0 && (
                        <div className="text-gray-500 dark:text-gray-400 text-xs">Value: {event.conversion_value}</div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {loading && (
          <div className="flex justify-center p-4">
            <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500" />
          </div>
        )}

        {!loading && hasMore && (
          <div className="flex justify-center p-4">
            <button
              onClick={loadMore}
              className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              Load More
            </button>
          </div>
        )}

        {!loading && Array.isArray(events) && events.length === 0 && (
          <div className="flex justify-center p-8 text-gray-500 dark:text-gray-400">
            No events found
          </div>
        )}
      </div>
    </div>
  );
}
