import React from 'react';
import { StatCard } from '../components/StatCard';
import { JobStatus } from '../components/JobStatus';

interface Job {
  id: string;
  location: string;
  status: 'pending' | 'running' | 'complete' | 'error';
  propertyCount: number;
  startedAt: string;
  propertyTypes?: string[];
}

interface DashboardData {
  totalLeads?: number;
  scrapedToday?: number;
  dailyLimitRemaining?: number;
  dailyLimit?: number;
  recentJobs?: Job[];
  propertyTypeBreakdown?: Record<string, number>;
}

interface DashboardProps {
  data: DashboardData;
}

// Simple CSS pie chart
function PieChart({ data }: { data: Record<string, number> }) {
  const total = Object.values(data).reduce((s, v) => s + v, 0);
  if (total === 0) return null;

  const colors = ['#00bcd4', '#4caf50', '#ff9800', '#f44336', '#9c27b0', '#2196f3', '#607d8b', '#e91e63'];
  let cumulative = 0;

  const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);

  const segments = entries.map(([label, value], idx) => {
    const pct = (value / total) * 100;
    const start = cumulative;
    cumulative += pct;
    return { label, value, pct, start, color: colors[idx % colors.length] };
  });

  // Build conic-gradient
  const gradientStops = segments
    .map((seg) => `${seg.color} ${seg.start}% ${seg.start + seg.pct}%`)
    .join(', ');

  return (
    <div className="flex items-center gap-6">
      <div
        className="w-32 h-32 rounded-full flex-shrink-0"
        style={{ background: `conic-gradient(${gradientStops})` }}
      />
      <div className="space-y-1.5 min-w-0">
        {segments.map((seg) => (
          <div key={seg.label} className="flex items-center gap-2 text-sm">
            <span
              className="w-3 h-3 rounded-sm flex-shrink-0"
              style={{ backgroundColor: seg.color }}
            />
            <span className="truncate text-gray-600">{seg.label}</span>
            <span className="font-medium text-gray-900 ml-auto">{seg.value}</span>
            <span className="text-gray-400 text-xs w-10 text-right">{seg.pct.toFixed(0)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

export function Dashboard({ data }: DashboardProps) {
  const {
    totalLeads = 0,
    scrapedToday = 0,
    dailyLimitRemaining = 50,
    dailyLimit = 50,
    recentJobs = [],
    propertyTypeBreakdown = {},
  } = data;

  const usagePct = dailyLimit > 0 ? ((dailyLimit - dailyLimitRemaining) / dailyLimit) * 100 : 0;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-reo-dark text-white px-6 py-4">
        <div className="flex items-center gap-3">
          <span className="w-8 h-8 bg-reo-teal rounded-lg flex items-center justify-center text-sm font-bold">R</span>
          <div>
            <h1 className="text-lg font-bold">Reonomy Dashboard</h1>
            <p className="text-xs text-gray-400">Property scraping overview</p>
          </div>
        </div>
      </div>

      <div className="px-6 py-5 space-y-6">
        {/* Stat Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <StatCard
            label="Total Leads"
            value={totalLeads.toLocaleString()}
            icon="🏢"
            color="teal"
          />
          <StatCard
            label="Scraped Today"
            value={scrapedToday.toLocaleString()}
            icon="📊"
            color="green"
            trend={scrapedToday > 0 ? { value: `${scrapedToday} new`, positive: true } : undefined}
          />
          <StatCard
            label="Daily Limit"
            value={`${dailyLimitRemaining}/${dailyLimit}`}
            icon="⏱️"
            color={dailyLimitRemaining < 10 ? 'orange' : 'blue'}
          />
        </div>

        {/* Usage bar */}
        <div className="bg-white rounded-lg border border-gray-200 p-4 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">Daily Usage</span>
            <span className="text-sm text-gray-500">{usagePct.toFixed(0)}%</span>
          </div>
          <div className="w-full h-2.5 bg-gray-100 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 ${
                usagePct > 80 ? 'bg-orange-500' : usagePct > 90 ? 'bg-red-500' : 'bg-reo-teal'
              }`}
              style={{ width: `${Math.min(usagePct, 100)}%` }}
            />
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Recent Jobs */}
          <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
            <div className="px-4 py-3 border-b border-gray-100">
              <h2 className="text-sm font-semibold text-gray-700">Recent Jobs</h2>
            </div>
            <div className="divide-y divide-gray-50">
              {recentJobs.length === 0 ? (
                <div className="px-4 py-8 text-center text-gray-400 text-sm">
                  No jobs yet. Start a search to begin scraping.
                </div>
              ) : (
                recentJobs.slice(0, 8).map((job) => (
                  <div key={job.id} className="px-4 py-3 flex items-center justify-between hover:bg-gray-50 transition-colors">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium text-reo-dark truncate">{job.location}</span>
                        <JobStatus status={job.status} />
                      </div>
                      <div className="flex items-center gap-3 mt-0.5 text-xs text-gray-400">
                        <span>{job.propertyCount} properties</span>
                        {job.propertyTypes && job.propertyTypes.length > 0 && (
                          <span>{job.propertyTypes.slice(0, 2).join(', ')}</span>
                        )}
                      </div>
                    </div>
                    <span className="text-xs text-gray-400 flex-shrink-0 ml-4">
                      {formatTimeAgo(job.startedAt)}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Property Type Breakdown */}
          <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
            <div className="px-4 py-3 border-b border-gray-100">
              <h2 className="text-sm font-semibold text-gray-700">Property Types</h2>
            </div>
            <div className="p-4">
              {Object.keys(propertyTypeBreakdown).length === 0 ? (
                <div className="py-8 text-center text-gray-400 text-sm">
                  Property breakdown will appear after scraping
                </div>
              ) : (
                <PieChart data={propertyTypeBreakdown} />
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function formatTimeAgo(dateStr: string): string {
  try {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMin = Math.floor(diffMs / 60000);
    if (diffMin < 1) return 'just now';
    if (diffMin < 60) return `${diffMin}m ago`;
    const diffHr = Math.floor(diffMin / 60);
    if (diffHr < 24) return `${diffHr}h ago`;
    const diffDay = Math.floor(diffHr / 24);
    return `${diffDay}d ago`;
  } catch {
    return dateStr;
  }
}
