"use client";

import { useState, useEffect } from 'react';
import { addDays, format } from 'date-fns';
import { DateRangePicker } from '../../components/ui/DateRangePicker';
import TimeSeriesChart from '../../components/charts/TimeSeriesChart';
import { TimeSeriesData } from '../../api/types';

interface ConversionStats {
  totalConversions: number;
  conversionRate: number;
  averageValue: number;
  conversionsByType: {
    type: string;
    count: number;
    value: number;
    percentage: number;
  }[];
}

export default function ConversionsPage() {
  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 [stats, setStats] = useState<ConversionStats | null>(null);
  const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);

      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 [statsRes, timeSeriesRes] = await Promise.all([
          fetch(`/api/events/conversions/stats?startTime=${startTime}&endTime=${endTime}`),
          fetch(`/api/events/conversions/time-series?startTime=${startTime}&endTime=${endTime}`)
        ]);

        const [statsData, timeSeriesData] = await Promise.all([
          statsRes.json(),
          timeSeriesRes.json()
        ]);

        if (!statsRes.ok) throw new Error(statsData.error || 'Failed to fetch conversion stats');
        if (!timeSeriesRes.ok) throw new Error(timeSeriesData.error || 'Failed to fetch time series data');

        setStats(statsData);
        setTimeSeriesData(timeSeriesData.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [dateRange]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500" />
      </div>
    );
  }

  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">Conversion Analytics</h1>
        <DateRangePicker
          value={dateRange}
          onChange={setDateRange}
        />
      </div>

      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Total Conversions</h3>
            <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">{stats.totalConversions.toLocaleString()}</p>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Conversion Rate</h3>
            <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">{stats.conversionRate.toFixed(2)}%</p>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Average Value</h3>
            <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">${stats.averageValue.toFixed(2)}</p>
          </div>
        </div>
      )}

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Conversion Trends</h2>
        <div className="h-96">
          <TimeSeriesChart data={timeSeriesData} />
        </div>
      </div>

      {stats && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Conversion Types</h2>
          <div className="space-y-6">
            {stats.conversionsByType.map((item, index) => (
              <div key={index}>
                <div className="flex justify-between items-center mb-2">
                  <div>
                    <span className="text-gray-900 dark:text-gray-100 font-medium">{item.type}</span>
                    <span className="text-gray-500 dark:text-gray-400 text-sm ml-2">
                      {item.count.toLocaleString()} conversions
                    </span>
                  </div>
                  <div className="text-right">
                    <span className="text-gray-900 dark:text-gray-100 font-medium">
                      ${item.value.toFixed(2)}
                    </span>
                    <span className="text-gray-500 dark:text-gray-400 text-sm ml-2">
                      ({item.percentage.toFixed(1)}%)
                    </span>
                  </div>
                </div>
                <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                  <div
                    className="bg-blue-500 h-2 rounded-full"
                    style={{ width: `${item.percentage}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
} 