import { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { getDashboardStats, getRecentClassifications } from '../services/api';
import type { DashboardStats, ClassificationResult } from '../types';

// Extended type to include stale indicator from API
interface DashboardStatsWithMeta extends DashboardStats {
  stale?: boolean;
  error?: string;
}

export default function Dashboard() {
  const [stats, setStats] = useState<DashboardStatsWithMeta | null>(null);
  const [recentClassifications, setRecentClassifications] = useState<ClassificationResult[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async (forceRefresh: boolean = false) => {
    if (forceRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);
    
    try {
      const [statsData, recentData] = await Promise.all([
        getDashboardStats(forceRefresh),
        getRecentClassifications(10),
      ]);
      setStats(statsData as DashboardStatsWithMeta);
      setRecentClassifications(recentData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load dashboard');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchData(false);
  }, [fetchData]);
  
  const handleRefresh = () => {
    fetchData(true);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
        {error}
      </div>
    );
  }

  const progressPercentage = stats
    ? Math.round((stats.classifiedCount / stats.totalApplications) * 100)
    : 0;

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Dashboard</h2>
          <p className="text-gray-600">
            Overzicht van de ZiRA classificatie voortgang
            {stats?.stale && (
              <span className="ml-2 text-amber-600 text-sm">
                (gecachte data - API timeout)
              </span>
            )}
          </p>
        </div>
        <div className="flex items-center space-x-3">
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            className="btn btn-secondary flex items-center space-x-2"
            title="Ververs data"
          >
            <svg
              className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
              />
            </svg>
            <span>{refreshing ? 'Laden...' : 'Ververs'}</span>
          </button>
          <Link to="/applications" className="btn btn-primary">
            Start classificeren
          </Link>
        </div>
      </div>

      {/* Stats cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="card p-6">
          <div className="text-sm text-gray-500 mb-1">Totaal applicaties</div>
          <div className="text-3xl font-bold text-gray-900">
            {stats?.totalApplications || 0}
          </div>
        </div>

        <div className="card p-6">
          <div className="text-sm text-gray-500 mb-1">Geclassificeerd</div>
          <div className="text-3xl font-bold text-green-600">
            {stats?.classifiedCount || 0}
          </div>
        </div>

        <div className="card p-6">
          <div className="text-sm text-gray-500 mb-1">Nog te classificeren</div>
          <div className="text-3xl font-bold text-orange-600">
            {Math.max(0, stats?.unclassifiedCount || 0)}
          </div>
        </div>

        <div className="card p-6">
          <div className="text-sm text-gray-500 mb-1">Voortgang</div>
          <div className="text-3xl font-bold text-blue-600">
            {progressPercentage}%
          </div>
        </div>
      </div>

      {/* Progress bar */}
      <div className="card p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-4">
          Classificatie voortgang
        </h3>
        <div className="space-y-2">
          <div className="flex justify-between text-sm text-gray-600">
            <span>ApplicationFunction ingevuld</span>
            <span>
              {stats?.classifiedCount || 0} / {stats?.totalApplications || 0}
            </span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-4">
            <div
              className="bg-blue-600 h-4 rounded-full transition-all duration-500"
              style={{ width: `${progressPercentage}%` }}
            />
          </div>
        </div>
      </div>

      {/* Two column layout */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Status distribution */}
        <div className="card p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            Verdeling per status
          </h3>
          <div className="space-y-3">
            {stats?.byStatus &&
              Object.entries(stats.byStatus)
                .sort((a, b) => {
                  // Sort alphabetically, but put "Undefined" at the end
                  if (a[0] === 'Undefined') return 1;
                  if (b[0] === 'Undefined') return -1;
                  return a[0].localeCompare(b[0], 'nl', { sensitivity: 'base' });
                })
                .map(([status, count]) => (
                  <div key={status} className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">{status}</span>
                    <div className="flex items-center space-x-2">
                      <div className="w-32 bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-blue-600 h-2 rounded-full"
                          style={{
                            width: `${(count / (stats?.totalApplications || 1)) * 100}%`,
                          }}
                        />
                      </div>
                      <span className="text-sm font-medium text-gray-900 w-8 text-right">
                        {count}
                      </span>
                    </div>
                  </div>
                ))}
          </div>
        </div>

        {/* Governance model distribution */}
        <div className="card p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            Verdeling per regiemodel
          </h3>
          <div className="space-y-3">
            {stats?.byGovernanceModel &&
              Object.entries(stats.byGovernanceModel)
                .sort((a, b) => {
                  // Sort alphabetically, but put "Niet ingesteld" at the end
                  if (a[0] === 'Niet ingesteld') return 1;
                  if (b[0] === 'Niet ingesteld') return -1;
                  return a[0].localeCompare(b[0], 'nl', { sensitivity: 'base' });
                })
                .map(([model, count]) => (
                  <div key={model} className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">{model}</span>
                    <div className="flex items-center space-x-2">
                      <div className="w-32 bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-purple-600 h-2 rounded-full"
                          style={{
                            width: `${(count / (stats?.totalApplications || 1)) * 100}%`,
                          }}
                        />
                      </div>
                      <span className="text-sm font-medium text-gray-900 w-8 text-right">
                        {count}
                      </span>
                    </div>
                  </div>
                ))}
            {(!stats?.byGovernanceModel ||
              Object.keys(stats.byGovernanceModel).length === 0) && (
              <p className="text-sm text-gray-500">Geen data beschikbaar</p>
            )}
          </div>
        </div>
      </div>

      {/* Recent classifications */}
      <div className="card">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">
            Recente classificaties
          </h3>
        </div>
        <div className="divide-y divide-gray-200">
          {recentClassifications.length === 0 ? (
            <div className="px-6 py-8 text-center text-gray-500">
              Nog geen classificaties uitgevoerd
            </div>
          ) : (
            recentClassifications.map((item, index) => (
              <div
                key={index}
                className="px-6 py-4 flex items-center justify-between hover:bg-gray-50"
              >
                <div>
                  <div className="font-medium text-gray-900">
                    {item.applicationName}
                  </div>
                  <div className="text-sm text-gray-500">
                    {item.changes.applicationFunctions && item.changes.applicationFunctions.to.length > 0 && (
                      <span>
                        ApplicationFunctions: {item.changes.applicationFunctions.to.map((f) => f.name).join(', ')}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex items-center space-x-3">
                  <span
                    className={`badge ${
                      item.source === 'AI_ACCEPTED'
                        ? 'badge-green'
                        : item.source === 'AI_MODIFIED'
                        ? 'badge-yellow'
                        : 'badge-blue'
                    }`}
                  >
                    {item.source === 'AI_ACCEPTED'
                      ? 'AI Geaccepteerd'
                      : item.source === 'AI_MODIFIED'
                      ? 'AI Aangepast'
                      : 'Handmatig'}
                  </span>
                  <span className="text-sm text-gray-500">
                    {new Date(item.timestamp).toLocaleString('nl-NL')}
                  </span>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
