'use client';

import { useState } from 'react';
import type { JobStatus } from '@ehandyhire/shared';
import { CUSTOMER_REOPENABLE_JOB_STATUSES } from '@ehandyhire/shared';
import { Button } from '@/components/ui/button';
import { api } from '@/lib/api';
import { CheckCircle2, Play, RotateCcw, XCircle } from 'lucide-react';

export type JobProgressAction =
  | 'start'
  | 'mark_complete'
  | 'confirm_complete'
  | 'cancel'
  | 'reopen';

interface JobProgressPanelProps {
  jobId: string;
  status: JobStatus;
  role: 'customer' | 'worker';
  workerMarkedCompleteAt?: string | null;
  onUpdated: (job: Record<string, unknown>) => void;
}

export function JobProgressPanel({
  jobId,
  status,
  role,
  workerMarkedCompleteAt,
  onUpdated,
}: JobProgressPanelProps) {
  const [loading, setLoading] = useState<JobProgressAction | null>(null);
  const [error, setError] = useState('');

  const runAction = async (action: JobProgressAction) => {
    setLoading(action);
    setError('');
    try {
      const res = await api<{ data: Record<string, unknown> }>(`/jobs/${jobId}/progress`, {
        method: 'POST',
        body: JSON.stringify({ action }),
      });
      onUpdated(res.data);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Action failed');
    } finally {
      setLoading(null);
    }
  };

  const showWorkerStart = role === 'worker' && status === 'ACCEPTED';
  const showWorkerComplete = role === 'worker' && status === 'IN_PROGRESS' && !workerMarkedCompleteAt;
  const showCustomerConfirm = role === 'customer' && status === 'IN_PROGRESS';
  const showCustomerCancel =
    role === 'customer' && ['ACCEPTED', 'IN_PROGRESS'].includes(status);
  const showCustomerReopen =
    role === 'customer' && CUSTOMER_REOPENABLE_JOB_STATUSES.includes(status);

  if (
    !showWorkerStart &&
    !showWorkerComplete &&
    !showCustomerConfirm &&
    !showCustomerCancel &&
    !showCustomerReopen
  ) {
    return null;
  }

  const reopenMessage =
    status === 'CANCELLED'
      ? 'Reopen this job so workers can send new quotes?'
      : 'Release the current worker and reopen this job for new quotes? The hired worker will be notified.';

  return (
    <section className="rounded-xl border border-border bg-surface p-4 md:p-5 space-y-3">
      <h2 className="font-bold text-slate-900">Next steps</h2>

      {error && (
        <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
          {error}
        </p>
      )}

      <div className="flex flex-wrap gap-2">
        {showWorkerStart && (
          <Button
            className="gap-2"
            onClick={() => runAction('start')}
            disabled={loading !== null}
          >
            <Play className="h-4 w-4" />
            {loading === 'start' ? 'Starting...' : 'Start job'}
          </Button>
        )}

        {showWorkerComplete && (
          <Button
            className="gap-2"
            onClick={() => runAction('mark_complete')}
            disabled={loading !== null}
          >
            <CheckCircle2 className="h-4 w-4" />
            {loading === 'mark_complete' ? 'Saving...' : 'Mark work as finished'}
          </Button>
        )}

        {showCustomerConfirm && (
          <Button
            className="gap-2"
            onClick={() => runAction('confirm_complete')}
            disabled={loading !== null}
          >
            <CheckCircle2 className="h-4 w-4" />
            {loading === 'confirm_complete' ? 'Confirming...' : 'Confirm work is done'}
          </Button>
        )}

        {showCustomerCancel && (
          <Button
            variant="outline"
            className="gap-2 text-red-600 border-red-200 hover:bg-red-50"
            onClick={() => {
              if (window.confirm('Cancel this job? The hired worker will be notified.')) {
                runAction('cancel');
              }
            }}
            disabled={loading !== null}
          >
            <XCircle className="h-4 w-4" />
            {loading === 'cancel' ? 'Cancelling...' : 'Cancel job'}
          </Button>
        )}

        {showCustomerReopen && (
          <Button
            variant="outline"
            className="gap-2"
            onClick={() => {
              if (window.confirm(reopenMessage)) {
                runAction('reopen');
              }
            }}
            disabled={loading !== null}
          >
            <RotateCcw className="h-4 w-4" />
            {loading === 'reopen' ? 'Reopening...' : 'Reopen for new quotes'}
          </Button>
        )}
      </div>

      {role === 'customer' && showCustomerReopen && status !== 'CANCELLED' && (
        <p className="text-sm text-muted">
          Use this if the hired worker is not a fit. The job will go back on the board for other
          workers to quote.
        </p>
      )}

      {role === 'worker' && status === 'IN_PROGRESS' && workerMarkedCompleteAt && (
        <p className="text-sm text-muted">
          Waiting for the customer to confirm completion.
        </p>
      )}
    </section>
  );
}
