'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { api } from '@/lib/api';
import {
  AdminEmpty,
  AdminError,
  AdminLoading,
  AdminTable,
  AdminTd,
  AdminTh,
  PaginationBar,
  PaginationMeta,
  StatusBadge,
  formatDate,
} from '@/components/admin/admin-ui';
import { WorkerProfileBadges, WorkerSkillsBadges } from '@/components/workers/WorkerProfileDisplay';
import { cn } from '@/lib/utils';

interface WorkerRow {
  id: string;
  displayName?: string | null;
  headline: string | null;
  isVerified: boolean;
  isStudent?: boolean;
  isAvailable: boolean;
  verificationStatus: string;
  otherSkills?: string | null;
  averageRating: number;
  totalJobs: number;
  createdAt?: string;
  user: {
    id: string;
    firstName: string;
    lastName: string;
    email: string | null;
    phone: string | null;
    status: string;
    phoneVerified?: boolean;
    emailVerified?: boolean;
    createdAt?: string;
    lastLoginAt?: string | null;
  };
  skills: { category: { name: string; slug?: string; id?: string } }[];
  _count: { reviewsReceived: number; verificationDocs?: number };
}

interface ListSummary {
  verified: number;
  unverified: number;
  phonePending: number;
  total: number;
}

type VerifyFilter = '' | 'true' | 'false';
type PhoneFilter = '' | 'true' | 'false';

export default function AdminWorkersPage() {
  const [workers, setWorkers] = useState<WorkerRow[]>([]);
  const [summary, setSummary] = useState<ListSummary | null>(null);
  const [meta, setMeta] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [search, setSearch] = useState('');
  const [verified, setVerified] = useState<VerifyFilter>('');
  const [phoneFilter, setPhoneFilter] = useState<PhoneFilter>('');
  const [accountStatus, setAccountStatus] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [updating, setUpdating] = useState<string | null>(null);

  const load = useCallback(
    async (page = 1) => {
      setLoading(true);
      setError('');
      try {
        const params = new URLSearchParams({ page: String(page), limit: '20' });
        if (search) params.set('search', search);
        if (verified) params.set('verified', verified);
        if (phoneFilter) params.set('phoneVerified', phoneFilter);
        if (accountStatus) params.set('status', accountStatus);
        const res = await api<{
          data: { items: WorkerRow[]; summary: ListSummary };
          meta: PaginationMeta;
        }>(`/workers/admin/list?${params}`);
        setWorkers(res.data.items);
        setSummary(res.data.summary);
        setMeta(res.meta!);
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Failed to load workers');
      } finally {
        setLoading(false);
      }
    },
    [search, verified, phoneFilter, accountStatus]
  );

  useEffect(() => {
    load(1);
  }, [load]);

  async function patchWorker(id: string, body: Record<string, unknown>) {
    setUpdating(id);
    try {
      await api(`/workers/admin/${id}`, {
        method: 'PATCH',
        body: JSON.stringify(body),
      });
      await load(meta.page);
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Update failed');
    } finally {
      setUpdating(null);
    }
  }

  const verifyTabs: { key: VerifyFilter; label: string; count?: number }[] = [
    { key: '', label: 'All', count: summary?.total },
    { key: 'false', label: 'Unverified', count: summary?.unverified },
    { key: 'true', label: 'Verified', count: summary?.verified },
  ];

  return (
    <DashboardLayout role="admin" title="Workers">
      <p className="mb-5 text-sm text-muted">
        Workers need a verified phone plus approved ID and selfie before their public profile is
        shown.
      </p>

      <div className="mb-5 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-2xl font-bold text-slate-900">{summary?.total ?? '—'}</p>
            <p className="text-xs text-muted">Total workers</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-2xl font-bold text-amber-600">{summary?.unverified ?? '—'}</p>
            <p className="text-xs text-muted">Unverified profiles</p>
            <button
              type="button"
              className="mt-2 text-xs font-semibold text-primary hover:underline"
              onClick={() => setVerified('false')}
            >
              Show unverified
            </button>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-2xl font-bold text-amber-600">{summary?.phonePending ?? '—'}</p>
            <p className="text-xs text-muted">Phone not verified</p>
            <button
              type="button"
              className="mt-2 text-xs font-semibold text-primary hover:underline"
              onClick={() => setPhoneFilter('false')}
            >
              Show phone pending
            </button>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-2xl font-bold text-emerald-700">{summary?.verified ?? '—'}</p>
            <p className="text-xs text-muted">Verified workers</p>
            <Link
              href="/admin/verifications?owner=worker&status=PENDING"
              className="mt-2 inline-block text-xs font-semibold text-primary hover:underline"
            >
              Pending docs queue
            </Link>
          </CardContent>
        </Card>
      </div>

      <div className="mb-4 flex flex-wrap gap-2 border-b border-border pb-3">
        {verifyTabs.map((tab) => {
          const active = verified === tab.key;
          return (
            <button
              key={tab.key || 'all'}
              type="button"
              onClick={() => setVerified(tab.key)}
              className={cn(
                'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-semibold transition-colors',
                active ? 'bg-primary text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
              )}
            >
              {tab.label}
              {typeof tab.count === 'number' ? (
                <span
                  className={cn(
                    'rounded-full px-1.5 py-0.5 text-[10px] font-bold',
                    active ? 'bg-white/20 text-white' : 'bg-white text-slate-600'
                  )}
                >
                  {tab.count}
                </span>
              ) : null}
            </button>
          );
        })}
      </div>

      <div className="mb-6 flex flex-col gap-3 lg:flex-row">
        <Input
          placeholder="Search name, display name, email, phone…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="flex-1"
        />
        <select
          value={phoneFilter}
          onChange={(e) => setPhoneFilter(e.target.value as PhoneFilter)}
          className="search-input h-11 rounded-md border border-border px-3"
        >
          <option value="">All phone status</option>
          <option value="true">Phone verified</option>
          <option value="false">Phone pending</option>
        </select>
        <select
          value={accountStatus}
          onChange={(e) => setAccountStatus(e.target.value)}
          className="search-input h-11 rounded-md border border-border px-3"
        >
          <option value="">All accounts</option>
          <option value="ACTIVE">Active</option>
          <option value="SUSPENDED">Suspended</option>
        </select>
        <Button onClick={() => load(1)}>Search</Button>
        <Link href="/admin/verifications?owner=worker&status=PENDING">
          <Button variant="outline">Pending docs</Button>
        </Link>
      </div>

      {loading && <AdminLoading />}
      {!loading && error && <AdminError message={error} />}
      {!loading && !error && workers.length === 0 && <AdminEmpty message="No workers found." />}
      {!loading && !error && workers.length > 0 && (
        <>
          <AdminTable>
            <thead>
              <tr>
                <AdminTh>Worker</AdminTh>
                <AdminTh>Contact</AdminTh>
                <AdminTh>Account checks</AdminTh>
                <AdminTh>Skills</AdminTh>
                <AdminTh>Verification</AdminTh>
                <AdminTh>Account</AdminTh>
                <AdminTh>Joined</AdminTh>
                <AdminTh>Actions</AdminTh>
              </tr>
            </thead>
            <tbody>
              {workers.map((worker) => {
                const displayName =
                  worker.displayName?.trim() ||
                  `${worker.user.firstName} ${worker.user.lastName}`;
                return (
                  <tr key={worker.id} className="hover:bg-slate-50/50">
                    <AdminTd>
                      <p className="font-medium text-slate-900">{displayName}</p>
                      <p className="text-xs text-muted">
                        Legal: {worker.user.firstName} {worker.user.lastName}
                      </p>
                      {worker.headline ? (
                        <p className="mt-0.5 line-clamp-1 text-xs text-slate-500">{worker.headline}</p>
                      ) : null}
                      <WorkerProfileBadges
                        isVerified={worker.isVerified}
                        isStudent={worker.isStudent}
                        className="mt-1.5"
                      />
                    </AdminTd>
                    <AdminTd>
                      <p className="text-sm">{worker.user.email || '—'}</p>
                      <p className="text-xs text-muted">{worker.user.phone || 'No phone'}</p>
                    </AdminTd>
                    <AdminTd>
                      <div className="space-y-1 text-xs">
                        <p className={worker.user.phoneVerified ? 'text-emerald-700' : 'text-amber-700'}>
                          Phone: {worker.user.phoneVerified ? 'Verified' : 'Pending'}
                        </p>
                        <p className={worker.user.emailVerified ? 'text-emerald-700' : 'text-slate-600'}>
                          Email: {worker.user.emailVerified ? 'Verified' : 'Unverified'}
                        </p>
                        <p className="text-muted">
                          Docs: {worker._count.verificationDocs ?? 0}
                        </p>
                      </div>
                    </AdminTd>
                    <AdminTd>
                      <WorkerSkillsBadges
                        skills={worker.skills}
                        otherSkills={worker.otherSkills}
                        limit={3}
                        showOverflow
                        badgeClassName="normal-case text-[10px]"
                      />
                    </AdminTd>
                    <AdminTd>
                      <div className="flex flex-col items-start gap-1">
                        {worker.isVerified ? (
                          <Badge variant="verified">Verified</Badge>
                        ) : (
                          <Badge variant="warning">Unverified</Badge>
                        )}
                        <span className="text-[10px] uppercase text-muted">
                          {worker.verificationStatus.replace(/_/g, ' ')}
                        </span>
                        <p className="text-xs text-muted">
                          {worker.averageRating.toFixed(1)} ★ · {worker._count.reviewsReceived} reviews
                        </p>
                      </div>
                    </AdminTd>
                    <AdminTd>
                      <div className="flex flex-col items-start gap-1">
                        <StatusBadge status={worker.user.status} />
                        <Badge
                          variant="secondary"
                          className={cn(
                            'normal-case text-[10px]',
                            worker.isAvailable
                              ? 'bg-emerald-50 text-emerald-800'
                              : 'bg-slate-100 text-slate-600'
                          )}
                        >
                          {worker.isAvailable ? 'Available' : 'Unavailable'}
                        </Badge>
                      </div>
                    </AdminTd>
                    <AdminTd>{formatDate(worker.user.createdAt)}</AdminTd>
                    <AdminTd>
                      <div className="flex flex-col gap-1.5">
                        <Link
                          href={`/admin/verifications?owner=worker&search=${encodeURIComponent(
                            worker.user.email || worker.user.firstName
                          )}`}
                        >
                          <Button size="sm" variant="outline" className="w-full">
                            Docs
                          </Button>
                        </Link>
                        <Button
                          size="sm"
                          variant="outline"
                          disabled={updating === worker.id}
                          onClick={() =>
                            patchWorker(worker.id, { isVerified: !worker.isVerified })
                          }
                        >
                          {worker.isVerified ? 'Unverify' : 'Verify'}
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          disabled={updating === worker.id}
                          onClick={() =>
                            patchWorker(worker.id, { isAvailable: !worker.isAvailable })
                          }
                        >
                          {worker.isAvailable ? 'Mark unavailable' : 'Mark available'}
                        </Button>
                      </div>
                    </AdminTd>
                  </tr>
                );
              })}
            </tbody>
          </AdminTable>
          <PaginationBar meta={meta} onPageChange={load} />
        </>
      )}
    </DashboardLayout>
  );
}
