import { useParams, Link } from 'react-router-dom';
import { useBrief, useSubmitBrief, useApproveBrief } from '../../hooks/useJob';
import { useAuthStore } from '../../lib/auth';
import { useToastContext } from '../../contexts/ToastContext';

const STATUS_BADGE: Record<string, string> = {
  draft: 'bg-gray-100 text-gray-700',
  submitted: 'bg-blue-100 text-blue-700',
  approved: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
  fulfilled: 'bg-purple-100 text-purple-700',
};

export function BriefDetail() {
  const { id } = useParams<{ id: string }>();
  const { user } = useAuthStore();
  const toast = useToastContext();

  const { data: brief, isLoading, error } = useBrief(id!);
  const submitMutation = useSubmitBrief();
  const approveMutation = useApproveBrief();

  const canSubmit = brief?.status === 'draft';
  const canApprove = brief?.status === 'submitted' && ['admin', 'project_manager'].includes(user?.role || '');
  const canCreateJob = brief?.status === 'approved';

  const handleSubmit = async () => {
    if (!id) return;
    try {
      await submitMutation.mutateAsync(id);
      toast.toastOnly.success('Brief submitted for approval');
    } catch {
      toast.toastOnly.error('Failed to submit brief');
    }
  };

  const handleApprove = async () => {
    if (!id) return;
    try {
      await approveMutation.mutateAsync(id);
      toast.toastOnly.success('Brief approved');
    } catch {
      toast.toastOnly.error('Failed to approve brief');
    }
  };

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8 animate-pulse">
        <div className="h-8 bg-gray-200 rounded w-1/3 mb-6"></div>
        <div className="h-64 bg-gray-200 rounded"></div>
      </div>
    );
  }

  if (error || !brief) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-600">Brief not found or access denied.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-3xl">
      <div className="flex items-center gap-3 mb-6">
        <Link to="/briefs" className="text-gray-500 hover:text-gray-700 text-sm">← Briefs</Link>
        <h1 className="text-2xl font-bold text-gray-900 flex-1">{brief.title}</h1>
        <span className={`px-3 py-1 rounded-full text-sm font-medium ${STATUS_BADGE[brief.status] ?? 'bg-gray-100 text-gray-700'}`}>
          {brief.status}
        </span>
      </div>

      <div className="bg-white border border-gray-200 rounded-lg p-6 space-y-4">
        {brief.description && (
          <div>
            <h3 className="text-sm font-medium text-gray-500">Description</h3>
            <p className="text-sm text-gray-800 mt-1">{brief.description}</p>
          </div>
        )}

        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-gray-500">Languages</span>
            <p className="text-gray-800 mt-0.5">{brief.languages.length > 0 ? brief.languages.map(l => l.toUpperCase()).join(', ') : '—'}</p>
          </div>
          <div>
            <span className="text-gray-500">Deadline</span>
            <p className="text-gray-800 mt-0.5">{brief.deadline ? new Date(brief.deadline).toLocaleDateString() : '—'}</p>
          </div>
          <div>
            <span className="text-gray-500">Created</span>
            <p className="text-gray-800 mt-0.5">{new Date(brief.created_at).toLocaleString()}</p>
          </div>
          {brief.submitted_at && (
            <div>
              <span className="text-gray-500">Submitted</span>
              <p className="text-gray-800 mt-0.5">{new Date(brief.submitted_at).toLocaleString()}</p>
            </div>
          )}
          {brief.job_id && (
            <div>
              <span className="text-gray-500">Linked Job</span>
              <Link to={`/jobs/${brief.job_id}`} className="text-indigo-600 hover:underline text-sm mt-0.5 block">
                View Job →
              </Link>
            </div>
          )}
        </div>

        <div>
          <h3 className="text-sm font-medium text-gray-500 mb-2">Requested Outputs</h3>
          <div className="flex flex-wrap gap-2 text-xs">
            {brief.requested_outputs.captions_vtt && <span className="bg-gray-100 px-2 py-1 rounded">Captions VTT</span>}
            {brief.requested_outputs.audio_description_vtt && <span className="bg-gray-100 px-2 py-1 rounded">AD VTT</span>}
            {brief.requested_outputs.audio_description_mp3 && <span className="bg-gray-100 px-2 py-1 rounded">AD MP3</span>}
            {brief.requested_outputs.sdh_vtt && <span className="bg-gray-100 px-2 py-1 rounded">SDH VTT</span>}
          </div>
        </div>
      </div>

      <div className="flex gap-3 mt-6">
        {canSubmit && (
          <button
            onClick={handleSubmit}
            disabled={submitMutation.isPending}
            className="px-5 py-2 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
          >
            {submitMutation.isPending ? 'Submitting...' : 'Submit for Approval'}
          </button>
        )}
        {canApprove && (
          <button
            onClick={handleApprove}
            disabled={approveMutation.isPending}
            className="px-5 py-2 bg-green-600 text-white text-sm rounded hover:bg-green-700 disabled:opacity-50"
          >
            {approveMutation.isPending ? 'Approving...' : 'Approve Brief'}
          </button>
        )}
        {canCreateJob && (
          <Link
            to={`/jobs/new?brief_id=${brief.id}`}
            className="px-5 py-2 bg-indigo-600 text-white text-sm rounded hover:bg-indigo-700"
          >
            Create Job from Brief
          </Link>
        )}
      </div>
    </div>
  );
}
