'use client';

import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';
import type { Deployment } from '@/lib/types';
import { BarChart3, TrendingUp, Clock, CheckCircle, XCircle } from 'lucide-react';
import { SidebarNav } from '@/components/sidebar-nav';

export default function MetricsPage() {
  const [deployments, setDeployments] = useState<Deployment[]>([]);
  const [loading, setLoading] = useState(true);

  const loadData = useCallback(async () => {
    try {
      const deploymentsData = await api.getDeployments(100);
      setDeployments(deploymentsData);
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
    }
  }, []);

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

  function getDeploymentStats() {
    const total = deployments.length;
    const success = deployments.filter(d => d.status === 'success').length;
    const failed = deployments.filter(d => d.status === 'failed').length;
    const running = deployments.filter(d => d.status === 'running').length;

    return { total, success, failed, running };
  }

  function getDeploymentsByService() {
    const serviceCount = new Map<string, number>();
    deployments.forEach(d => {
      serviceCount.set(d.serviceId, (serviceCount.get(d.serviceId) || 0) + 1);
    });
    return Array.from(serviceCount.entries()).sort((a, b) => b[1] - a[1]);
  }

  function getAverageDeploymentTime() {
    const completedDeployments = deployments.filter(d => d.completedAt);
    if (completedDeployments.length === 0) return 0;

    const totalTime = completedDeployments.reduce((sum, d) => {
      const start = new Date(d.triggeredAt).getTime();
      const end = new Date(d.completedAt!).getTime();
      return sum + (end - start);
    }, 0);

    return Math.round(totalTime / completedDeployments.length / 1000);
  }

  function getDeploymentTrend() {
    const last7Days = Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - i);
      return date.toISOString().split('T')[0];
    }).reverse();

    const trend = last7Days.map(date => {
      const dayDeployments = deployments.filter(d =>
        d.triggeredAt.startsWith(date)
      );
      return {
        date,
        count: dayDeployments.length,
        success: dayDeployments.filter(d => d.status === 'success').length,
        failed: dayDeployments.filter(d => d.status === 'failed').length,
      };
    });

    return trend;
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-gray-600">Loading...</div>
      </div>
    );
  }

  const stats = getDeploymentStats();
  const deploymentsByService = getDeploymentsByService();
  const avgDeploymentTime = getAverageDeploymentTime();
  const deploymentTrend = getDeploymentTrend();
  const maxCount = Math.max(...deploymentTrend.map(d => d.count), 1);

  return (
    <div className="flex min-h-screen bg-gray-50">
      <SidebarNav />

      <main className="flex-1 min-w-0 overflow-y-auto">
        <div className="p-8 max-md:p-4">
          <div className="mb-8">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Metrics & Analytics</h1>
              <p className="text-sm text-gray-600">Deployment statistics and trends</p>
            </div>
          </div>
        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Total Deployments</p>
                <p className="text-3xl font-bold text-gray-900">{stats.total}</p>
              </div>
              <BarChart3 className="w-8 h-8 text-blue-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Success Rate</p>
                <p className="text-3xl font-bold text-green-600">
                  {stats.total > 0 ? Math.round((stats.success / stats.total) * 100) : 0}%
                </p>
              </div>
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Failed</p>
                <p className="text-3xl font-bold text-red-600">{stats.failed}</p>
              </div>
              <XCircle className="w-8 h-8 text-red-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Avg Time</p>
                <p className="text-3xl font-bold text-blue-600">{avgDeploymentTime}s</p>
              </div>
              <Clock className="w-8 h-8 text-blue-600" />
            </div>
          </div>
        </div>

        {/* Deployment Trend Chart */}
        <div className="bg-white border border-gray-200 rounded-lg p-6 mb-8">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Deployment Trend (Last 7 Days)</h2>
          {deployments.length === 0 ? (
            <div className="h-48 flex items-center justify-center text-sm text-gray-400">
              No deployment data yet
            </div>
          ) : (
            <>
              {/* Bar chart — each column is a flex column-reverse so bars grow from bottom */}
              <div className="flex items-end justify-between gap-2 h-48">
                {deploymentTrend.map((day) => (
                  <div key={day.date} className="flex-1 flex flex-col items-center gap-1">
                    {/* Count label above bars */}
                    <span className="text-xs font-medium text-gray-500 mb-1">
                      {day.count > 0 ? day.count : ''}
                    </span>
                    {/* Stacked bar (grows upward via flex-col-reverse) */}
                    <div
                      className="w-full flex flex-col-reverse gap-px overflow-hidden rounded-sm"
                      style={{ height: `${Math.max((day.count / maxCount) * 160, day.count > 0 ? 4 : 0)}px` }}
                    >
                      {day.failed > 0 && (
                        <div
                          className="w-full bg-red-500 flex-shrink-0"
                          style={{ height: `${(day.failed / day.count) * 100}%` }}
                          title={`Failed: ${day.failed}`}
                        />
                      )}
                      {day.success > 0 && (
                        <div
                          className="w-full bg-green-500 flex-shrink-0"
                          style={{ height: `${(day.success / day.count) * 100}%` }}
                          title={`Success: ${day.success}`}
                        />
                      )}
                    </div>
                    <div className="mt-1 text-xs text-gray-500">
                      {new Date(day.date + 'T12:00:00').toLocaleDateString('en', { weekday: 'short' })}
                    </div>
                  </div>
                ))}
              </div>
              <div className="flex items-center justify-center gap-6 mt-3">
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-green-500 rounded-sm" />
                  <span className="text-sm text-gray-600">Success</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-red-500 rounded-sm" />
                  <span className="text-sm text-gray-600">Failed</span>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Deployments by Service */}
        <div className="bg-white border border-gray-200 rounded-lg p-6 mb-8">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Deployments by Service</h2>
          <div className="space-y-4">
            {deploymentsByService.map(([serviceId, count]) => {
              const percentage = (count / stats.total) * 100;
              return (
                <div key={serviceId}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm font-medium text-gray-900">{serviceId}</span>
                    <span className="text-sm text-gray-500">{count} deployments ({percentage.toFixed(1)}%)</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-blue-600 h-2 rounded-full"
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Success Rate by Service */}
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Success Rate by Service</h2>
          <div className="space-y-4">
            {deploymentsByService.map(([serviceId]) => {
              const serviceDeployments = deployments.filter(d => d.serviceId === serviceId);
              const success = serviceDeployments.filter(d => d.status === 'success').length;
              const rate = serviceDeployments.length > 0 ? (success / serviceDeployments.length) * 100 : 0;

              return (
                <div key={serviceId}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm font-medium text-gray-900">{serviceId}</span>
                    <span className="text-sm text-gray-500">{rate.toFixed(1)}%</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className={`h-2 rounded-full ${
                        rate >= 90 ? 'bg-green-600' : rate >= 70 ? 'bg-yellow-600' : 'bg-red-600'
                      }`}
                      style={{ width: `${rate}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </main>
    </div>
  );
}
