import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import { Zap, CheckCircle2, Clock, XCircle, Activity, Plus } from 'lucide-react';
import { Workflow } from '../types/workflow';
import { activityService } from '../services/activity';
import { ActivityLog } from '../types/activity';
import { __, sprintf } from '../lib/i18n';

interface DashboardProps {
  workflows: Workflow[];
  onNavigate?: (screen: string) => void;
}

export default function Dashboard({ workflows, onNavigate }: DashboardProps) {
  const [recentActivity, setRecentActivity] = useState<ActivityLog[]>([]);

  useEffect(() => {
    const fetchRecentActivity = async () => {
      try {
        const logs = await activityService.getActivityLogs({ limit: 4 });
        setRecentActivity(logs);
      } catch (err) {
        console.error('Error fetching recent activity:', err);
      }
    };
    fetchRecentActivity();
  }, []);

  const activeWorkflows = workflows.filter((w) => w.status === 'active');
  const totalExecutions = recentActivity.length;
  const successfulExecutions = recentActivity.filter((log) => log.level === 'info').length;
  const successRate =
    totalExecutions > 0 ? ((successfulExecutions / totalExecutions) * 100).toFixed(1) : '0.0';

  return (
    <div className="space-y-6">
      {/* Header - Using Sequensy Typography */}
      <div>
        <h1 className="seq-page-title">{__('Dashboard')}</h1>
        <p className="seq-body mt-1">{__('Monitor your workflow automation performance')}</p>
      </div>

      {/* Stats Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card className="card-hover relative overflow-hidden group">
          <Zap className="absolute -right-2 -bottom-2 h-20 w-20 text-success opacity-5 group-hover:opacity-10 transition-opacity" />
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-slate-500">
              {__('Active Workflows')}
            </CardTitle>
            <div className="p-2 rounded-lg bg-success-muted">
              <Zap className="h-4 w-4 text-success" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold font-display text-slate-900">
              {activeWorkflows.length}/{workflows.length}
            </div>
            <p className="text-xs text-slate-500 mt-1">{__('Currently active')}</p>
          </CardContent>
        </Card>

        <Card className="card-hover relative overflow-hidden group">
          <Activity className="absolute -right-2 -bottom-2 h-20 w-20 text-info opacity-5 group-hover:opacity-10 transition-opacity" />
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-slate-500">
              {__('Total Workflows')}
            </CardTitle>
            <div className="p-2 rounded-lg bg-info-muted">
              <Activity className="h-4 w-4 text-info" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold font-display text-slate-900">{workflows.length}</div>
            <p className="text-xs text-slate-500 mt-1">{__('Total configured')}</p>
          </CardContent>
        </Card>

        <Card className="card-hover relative overflow-hidden group">
          <CheckCircle2 className="absolute -right-2 -bottom-2 h-20 w-20 text-success opacity-5 group-hover:opacity-10 transition-opacity" />
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-slate-500">
              {__('Success Rate')}
            </CardTitle>
            <div
              className={`p-2 rounded-lg ${parseFloat(successRate) >= 90 ? 'bg-success-muted' : parseFloat(successRate) >= 70 ? 'bg-warning-muted' : 'bg-error-muted'}`}
            >
              <CheckCircle2
                className={`h-4 w-4 ${parseFloat(successRate) >= 90 ? 'text-success' : parseFloat(successRate) >= 70 ? 'text-warning' : 'text-error'}`}
              />
            </div>
          </CardHeader>
          <CardContent>
            <div
              className={`text-2xl font-bold font-display ${parseFloat(successRate) >= 90 ? 'text-success' : parseFloat(successRate) >= 70 ? 'text-warning' : 'text-slate-900'}`}
            >
              {successRate}%
            </div>
            <p className="text-xs text-slate-500 mt-1">{__('Based on recent activity')}</p>
          </CardContent>
        </Card>

        <Card className="card-hover relative overflow-hidden group">
          <Clock className="absolute -right-2 -bottom-2 h-20 w-20 text-slate-500 opacity-5 group-hover:opacity-10 transition-opacity" />
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-slate-500">
              {__('Total Executions')}
            </CardTitle>
            <div className="p-2 rounded-lg bg-slate-100">
              <Clock className="h-4 w-4 text-slate-500" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold font-display text-slate-900">{totalExecutions}</div>
            <p className="text-xs text-slate-500 mt-1">{__('Recent activity')}</p>
          </CardContent>
        </Card>
      </div>

      {/* Active Workflows & Recent Activity */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Active Workflows */}
        <Card>
          <CardHeader className="border-b border-slate-200">
            <CardTitle className="text-base">{__('Active Workflows')}</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {activeWorkflows.length === 0 ? (
              <div className="p-8 flex flex-col items-center text-center">
                <div className="w-12 h-12 rounded-full bg-success-muted flex items-center justify-center mb-4">
                  <Zap className="h-6 w-6 text-success" />
                </div>
                <h4 className="font-medium text-slate-900 mb-1">{__('No active workflows')}</h4>
                <p className="text-sm text-slate-500 mb-4">
                  {__('Create and activate a workflow to start automating.')}
                </p>
                <Button
                  size="sm"
                  variant="accent"
                  onClick={() => onNavigate?.('workflows')}
                >
                  <Plus className="h-4 w-4 mr-2" />
                  {__('Create Workflow')}
                </Button>
              </div>
            ) : (
              <div className="divide-y divide-slate-200">
                {activeWorkflows.slice(0, 3).map((workflow) => (
                  <div key={workflow.id} className="p-4 hover:bg-slate-50 transition-colors">
                    <div className="flex items-start justify-between mb-2">
                      <h4 className="font-medium text-sm text-slate-900">{workflow.name}</h4>
                      <Badge variant="success" className="text-xs">
                        {__('Active')}
                      </Badge>
                    </div>
                    <p className="text-xs text-slate-500 mb-2">
                      {workflow.trigger_type} → {Object.keys(workflow.draft_config?.actions ?? {}).length || 0}{' '}
                      {Object.keys(workflow.draft_config?.actions ?? {}).length === 1 ? __('action') : __('actions')}
                    </p>
                    <div className="flex items-center gap-4 text-xs text-slate-500">
                      <span>
                        {sprintf(
                          __('Updated: %s'),
                          new Date(workflow.updated_at).toLocaleDateString(),
                        )}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card>
          <CardHeader className="border-b border-slate-200">
            <CardTitle className="text-base">{__('Recent Activity')}</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {recentActivity.length === 0 ? (
              <div className="p-8 text-center text-sm text-slate-500">
                {__('No recent activity. Workflows will appear here after they execute.')}
              </div>
            ) : (
              <div className="divide-y divide-slate-200">
                {recentActivity.map((log) => (
                  <div key={log.id} className="p-4 hover:bg-slate-50 transition-colors">
                    <div className="flex items-start gap-3">
                      {log.level === 'info' ? (
                        <CheckCircle2 className="h-5 w-5 text-success flex-shrink-0 mt-0.5" />
                      ) : (
                        <XCircle className="h-5 w-5 text-error flex-shrink-0 mt-0.5" />
                      )}
                      <div className="flex-1">
                        <h4 className="font-medium text-sm text-slate-900 mb-1">
                          {sprintf(__('Workflow #%s'), log.workflow_id)}
                        </h4>
                        <p
                          className={`text-xs mb-1 ${log.level === 'error' || log.level === 'critical' ? 'text-error' : 'text-slate-500'}`}
                        >
                          {log.message}
                        </p>
                        <p className="text-xs text-slate-400">
                          {new Date(log.created_at).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
