'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Bell,
  Bookmark,
  Briefcase,
  ClipboardList,
  MessageCircle,
  ShieldCheck,
  Star,
  Users,
} from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  PortalShell,
  PortalSection,
  QuickLink,
} from '@/components/portal/Portal';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { cn } from '@/lib/utils';

export default function CustomerDashboard() {
  const { user } = useAuth();
  const [stats, setStats] = useState<Record<string, number>>({});

  useEffect(() => {
    api<{ data: { stats: Record<string, number> } }>('/users/customer/dashboard')
      .then((res) => setStats(res.data.stats))
      .catch(console.error);
  }, []);

  const jobStatCards = [
    {
      label: 'Open Jobs',
      value: stats.openJobs || 0,
      icon: Briefcase,
      color: 'bg-blue-50 text-primary',
      href: '/customer/jobs',
    },
    {
      label: 'Active Jobs',
      value: stats.activeJobs || 0,
      icon: MessageCircle,
      color: 'bg-amber-50 text-amber-600',
      href: '/customer/jobs',
    },
    {
      label: 'Completed',
      value: stats.completedJobs || 0,
      icon: Star,
      color: 'bg-emerald-50 text-accent',
      href: '/customer/jobs',
    },
    {
      label: 'Notifications',
      value: stats.unreadNotifications || 0,
      icon: Bell,
      color: 'bg-red-50 text-red-600',
      href: '/customer/notifications',
    },
  ];

  const directoryStatCards = [
    {
      label: 'Saved Workers',
      value: stats.savedWorkers || 0,
      icon: Bookmark,
      color: 'bg-blue-50 text-primary',
      href: '/customer/saved-workers',
    },
    {
      label: 'Messages',
      value: stats.unreadMessages || 0,
      icon: MessageCircle,
      color: 'bg-amber-50 text-amber-600',
      href: '/customer/messages',
    },
    {
      label: 'Notifications',
      value: stats.unreadNotifications || 0,
      icon: Bell,
      color: 'bg-red-50 text-red-600',
      href: '/customer/notifications',
    },
    {
      label: 'Reviews',
      value: stats.reviewsGiven || 0,
      icon: Star,
      color: 'bg-emerald-50 text-accent',
      href: '/customer/reviews',
    },
  ];

  const statCards = JOBS_FEATURE_ENABLED ? jobStatCards : directoryStatCards;
  const customerProfile = user?.customerProfile as
    | { isVerified?: boolean; verificationStatus?: string }
    | undefined;
  const isCustomerVerified = customerProfile?.isVerified === true;

  return (
    <DashboardLayout role="customer" title={`Hello, ${user?.firstName || 'Customer'}!`}>
      <PortalShell>
        {!isCustomerVerified && (
          <Card className="border-amber-200 bg-amber-50">
            <CardContent className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-start gap-3">
                <ShieldCheck className="mt-0.5 h-6 w-6 shrink-0 text-amber-600" />
                <div>
                  <p className="font-semibold text-slate-900">Verify your identity to hire</p>
                  <p className="text-sm text-muted">
                    Upload your government ID and selfie. Hiring stays locked until admin approval —
                    this helps protect workers.
                  </p>
                </div>
              </div>
              <Link href="/customer/verification">
                <Button size="sm" className="rounded-none">
                  Upload documents
                </Button>
              </Link>
            </CardContent>
          </Card>
        )}

        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
          {statCards.map((s) => (
            <Link key={s.label} href={s.href}>
              <Card className="h-full transition-shadow hover:shadow-md">
                <CardContent className="flex items-center gap-3 p-4">
                  <div
                    className={cn(
                      'flex h-10 w-10 shrink-0 items-center justify-center rounded-lg',
                      s.color
                    )}
                  >
                    <s.icon className="h-5 w-5" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold text-slate-900">{s.value}</p>
                    <p className="text-xs text-muted">{s.label}</p>
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>

        <PortalSection
          icon={JOBS_FEATURE_ENABLED ? Briefcase : Users}
          title="Quick actions"
          description="Jump to the most common tasks in your portal."
        >
          <div className="grid gap-3 sm:grid-cols-2">
            {JOBS_FEATURE_ENABLED && (
              <>
                <QuickLink
                  href="/customer/jobs/create"
                  icon={ClipboardList}
                  label="Post a job"
                  description="Describe work and get quotes from workers"
                />
                <QuickLink
                  href="/customer/jobs"
                  icon={Briefcase}
                  label="My jobs"
                  description="Track open, active, and completed jobs"
                />
              </>
            )}
            <QuickLink
              href="/workers"
              icon={Users}
              label="Browse workers"
              description="Discover skilled workers in your area"
            />
            <QuickLink
              href="/customer/saved-workers"
              icon={Bookmark}
              label="Saved workers"
              description="Re-hire workers you've bookmarked"
            />
            <QuickLink
              href="/customer/messages"
              icon={MessageCircle}
              label="Messages"
              description="Chat with workers about your needs"
            />
            <QuickLink
              href="/customer/reviews"
              icon={Star}
              label="Reviews"
              description="Rate workers you've worked with"
            />
            <QuickLink
              href="/customer/verification"
              icon={ShieldCheck}
              label="Verification"
              description="Upload ID docs to unlock hiring"
            />
          </div>
        </PortalSection>

        <Card className="border-primary/20 bg-primary/5">
          <CardContent className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="font-semibold text-slate-900">
                {JOBS_FEATURE_ENABLED ? 'Need help with something?' : 'Looking for a skilled worker?'}
              </p>
              <p className="text-sm text-muted">
                {JOBS_FEATURE_ENABLED
                  ? 'Post a job and receive quotations from workers in your area.'
                  : 'Browse the directory and message verified professionals near you.'}
              </p>
            </div>
            <Link href={JOBS_FEATURE_ENABLED ? '/customer/jobs/create' : '/workers'}>
              <Button size="sm" variant="accent">
                {JOBS_FEATURE_ENABLED ? 'Create job' : 'Browse workers'}
              </Button>
            </Link>
          </CardContent>
        </Card>
      </PortalShell>
    </DashboardLayout>
  );
}
