import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Layout from '../../components/Layout';
import StatusBadge from '../../components/StatusBadge';
import { supabase } from '../../lib/supabase';
import { useAuth } from '../../context/AuthContext';
import { withTimeout } from '../../lib/withTimeout';

function TaskRow({ task, project }) {
  return (
    <Link
      to={`/my-requests/${task.id}`}
      className="interactive-row"
      style={{
        display: 'flex', flexDirection: 'column', gap: 4,
        padding: '10px 14px', borderBottom: '1px solid var(--border)',
        textDecoration: 'none', cursor: 'pointer',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>{task.title}</span>
        <StatusBadge status={task.status} />
      </div>
      <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{project?.name || '—'}</span>
    </Link>
  );
}

function TaskColumn({ title, tasks, projects, emptyMessage }) {
  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '12px 14px', borderBottom: tasks.length > 0 ? '1px solid var(--border)' : 'none', background: 'var(--card-bg-2)' }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' }}>{title}</span>
        {tasks.length > 0 && (
          <span style={{ marginLeft: 8, fontSize: 11, fontWeight: 600, padding: '1px 7px', borderRadius: 20, background: 'var(--accent)', color: '#1a1a1a' }}>
            {tasks.length}
          </span>
        )}
      </div>
      {tasks.length === 0 ? (
        <div style={{ padding: '14px', fontSize: 13, color: 'var(--text-muted)' }}>{emptyMessage}</div>
      ) : (
        tasks.map(task => (
          <TaskRow key={task.id} task={task} project={projects.find(p => p.id === task.project_id)} />
        ))
      )}
    </div>
  );
}

export default function ClientDashboard() {
  const { currentUser } = useAuth();
  const hasCompany = Boolean(currentUser?.company_id || currentUser?.company?.id || currentUser?.companies?.length);

  const [stats, setStats] = useState({ notStarted: 0, inProgress: 0, awaitingReview: 0, outstandingInvoices: 0 });
  const [reviewTasks, setReviewTasks] = useState([]);
  const [inProgressTasks, setInProgressTasks] = useState([]);
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(hasCompany);

  useEffect(() => {
    if (!hasCompany) { setLoading(false); return; }

    async function load() {
      try {
        const [
          { count: notStartedCount },
          { count: inProgressCount },
          { count: reviewCount },
          { data: sentInvoices },
          { data: activeTasks },
        ] = await withTimeout(Promise.all([
          supabase.from('tasks').select('id', { count: 'exact', head: true }).eq('status', 'not_started'),
          supabase.from('tasks').select('id', { count: 'exact', head: true }).in('status', ['in_progress', 'on_hold']),
          supabase.from('tasks').select('id', { count: 'exact', head: true }).eq('status', 'client_review'),
          supabase.from('invoices').select('total').eq('status', 'sent'),
          supabase.from('tasks').select('id, title, status, project_id').in('status', ['client_review', 'in_progress', 'on_hold', 'not_started']).order('submitted_at', { ascending: false }),
        ]), 12000, 'Client dashboard load');

        setStats({
          notStarted: notStartedCount || 0,
          inProgress: inProgressCount || 0,
          awaitingReview: reviewCount || 0,
          outstandingInvoices: (sentInvoices || []).reduce((sum, inv) => sum + Number(inv.total || 0), 0),
        });

        const tasks = activeTasks || [];
        const review = tasks.filter(t => t.status === 'client_review');
        const inProg = tasks.filter(t => ['in_progress', 'on_hold', 'not_started'].includes(t.status));
        setReviewTasks(review);
        setInProgressTasks(inProg);

        if (tasks.length > 0) {
          const projectIds = [...new Set(tasks.map(t => t.project_id).filter(Boolean))];
          const { data: proj } = await supabase.from('projects').select('id, name').in('id', projectIds);
          setProjects(proj || []);
        }
      } catch (error) {
        console.error('ClientDashboard load failed:', error);
      } finally {
        setLoading(false);
      }
    }

    load();
  }, [hasCompany]);

  if (loading) return <Layout><p style={{ padding: 24, color: 'var(--text-muted)' }}>Loading...</p></Layout>;

  return (
    <Layout>
      <div className="page-header">
        <div>
          <div className="page-title">Welcome back, {currentUser?.name?.split(' ')[0]}</div>
          <div className="page-subtitle">Track active work and the items that need your attention.</div>
        </div>
        <Link to="/new-request" className="btn btn-primary">+ New Request</Link>
      </div>

      <div className="stats-grid">
        <div className="stat-card stat-card-highlight">
          <div className="stat-value" style={{ color: stats.awaitingReview > 0 ? 'var(--accent)' : undefined }}>{stats.awaitingReview}</div>
          <div className="stat-label">Awaiting Review</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">{stats.inProgress}</div>
          <div className="stat-label">In Progress</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">{stats.notStarted}</div>
          <div className="stat-label">Not Started</div>
        </div>
        <div className="stat-card">
          <div className="stat-value" style={{ fontSize: 22 }}>${stats.outstandingInvoices.toFixed(2)}</div>
          <div className="stat-label">Outstanding Invoices</div>
        </div>
      </div>

      <div className="grid-2" style={{ marginTop: 24 }}>
        <TaskColumn
          title="Awaiting Your Review"
          tasks={reviewTasks}
          projects={projects}
          emptyMessage="No items need your review."
        />
        <TaskColumn
          title="In Progress"
          tasks={inProgressTasks}
          projects={projects}
          emptyMessage="No items currently in progress."
        />
      </div>
    </Layout>
  );
}
