'use client';

import * as Sentry from '@sentry/nextjs';
import React, { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { toast } from '@/components/toast/Toast';
import { useModalContext } from '@/context/ModalContext';

import MarketplaceListingPreview from '../shared/MarketplaceListingPreview';

const MarketplaceEditListingModal: React.FC = () => {
  const { closeModal, getModalData } = useModalContext();
  const data = getModalData(ModalTypes.MARKETPLACE_EDIT_LISTING);
  const { apiClient } = useStores();

  const [title, setTitle] = useState(data?.title || '');
  const [summary, setSummary] = useState(
    data?.summary || data?.description || ''
  );
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Update form when modal data changes
  useEffect(() => {
    if (data) {
      setTitle(data.title || '');
      setSummary(data.summary || data.description || '');
    }
  }, [data]);

  const onClose = () => {
    closeModal(ModalTypes.MARKETPLACE_EDIT_LISTING);
  };

  const handleSave = async () => {
    if (!data || !title.trim() || !summary.trim()) return;

    setIsLoading(true);
    setError(null);

    try {
      await apiClient.PUT('/api/marketplace/projects/{project_id}/', {
        params: { path: { project_id: data.projectId } },
        body: {
          title: title.trim(),
          summary: summary.trim(),
        },
      });

      // Call the callback if provided - let parent components handle the refresh
      if (data.onSaveComplete) {
        data.onSaveComplete();
      }

      // Show success toast
      toast({
        title: 'Listing updated',
        description: 'Your listing changes have been saved successfully.',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });

      onClose();
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to save listing';

      // Log to Sentry
      Sentry.captureException(err, {
        tags: {
          component: 'MarketplaceEditListingModal',
          action: 'handleSave',
        },
        extra: {
          projectId: data.projectId,
          title: title.trim(),
          summary: summary.trim(),
        },
      });

      // Show error toast
      toast({
        title: 'Failed to save listing',
        description: errorMessage,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });

      // Set error state for UI display
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  if (!data) return null;

  return (
    <div className='fixed inset-0 z-50 flex items-center justify-center'>
      {/* Backdrop */}
      <div
        className='absolute inset-0 bg-black/50 backdrop-blur-sm'
        onClick={onClose}
        onKeyDown={(e) => e.key === 'Escape' && onClose()}
        role='button'
        tabIndex={0}
        aria-label='Close modal'
      />

      {/* Modal */}
      <div className='relative mx-4 flex max-h-[90vh] w-full max-w-4xl flex-col rounded-2xl bg-background-primary'>
        {/* Header */}
        <div className='flex items-center justify-between border-b border-border-primary px-6 py-4'>
          <h2 className='text-lg font-semibold text-foreground-primary'>
            Edit Listing Preview
          </h2>
          <button
            onClick={onClose}
            className='text-foreground-secondary transition-colors hover:text-foreground-primary'
          >
            <svg
              className='h-6 w-6'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M6 18L18 6M6 6l12 12'
              />
            </svg>
          </button>
        </div>

        {/* Content */}
        <div className='flex-1 overflow-y-auto p-6'>
          <div className='space-y-6'>
            <div className='mb-8 text-center'>
              <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                Listing Preview
              </h3>
              <p className='text-sm text-foreground-secondary'>
                Edit the title and summary that will be shown to editors in the
                marketplace.
              </p>
            </div>

            {/* Error Message */}
            {error && (
              <div className='rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3'>
                <div className='flex items-start gap-3'>
                  <svg
                    className='h-5 w-5 flex-shrink-0 text-red-400'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2}
                      d='M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'
                    />
                  </svg>
                  <div className='flex-1'>
                    <p className='text-sm font-medium text-red-400'>
                      Error saving listing
                    </p>
                    <p className='mt-1 text-sm text-red-300'>{error}</p>
                  </div>
                  <button
                    onClick={() => setError(null)}
                    className='text-red-400 transition-colors hover:text-red-300'
                    aria-label='Dismiss error'
                  >
                    <svg
                      className='h-4 w-4'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M6 18L18 6M6 6l12 12'
                      />
                    </svg>
                  </button>
                </div>
              </div>
            )}

            <div className='grid grid-cols-1 gap-6 lg:grid-cols-2'>
              {/* Left Column - Input Fields */}
              <div className='space-y-6'>
                {/* Project Title */}
                <div>
                  <label
                    htmlFor='edit-project-title'
                    className='mb-2 block text-sm font-medium text-foreground-primary'
                  >
                    Project Title <span className='text-red-400'>*</span>
                  </label>
                  <p className='mb-2 text-xs text-foreground-secondary'>
                    A descriptive title to grab the attention of editors.
                  </p>
                  <input
                    id='edit-project-title'
                    type='text'
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    placeholder='e.g. Mix graduation song'
                    required
                    className='w-full rounded-lg border border-border-primary bg-transparent px-3 py-2 text-sm text-foreground-primary placeholder-foreground-tertiary focus:border-pink-500 focus:outline-none'
                  />
                </div>

                {/* Project Summary */}
                <div>
                  <label
                    htmlFor='edit-project-summary'
                    className='mb-2 block text-sm font-medium text-foreground-primary'
                  >
                    Marketplace Summary <span className='text-red-400'>*</span>
                  </label>
                  <p className='mb-2 text-xs text-foreground-secondary'>
                    A concise and clear summary of your asks that will appear in
                    marketplace listings.
                  </p>
                  <textarea
                    id='edit-project-summary'
                    value={summary}
                    onChange={(e) => setSummary(e.target.value)}
                    rows={6}
                    placeholder='e.g. Need vocals louder and clearer with reverb'
                    required
                    className='w-full resize-none rounded-lg border border-border-primary bg-transparent px-3 py-2 text-sm text-foreground-primary placeholder-foreground-tertiary focus:border-pink-500 focus:outline-none'
                  />
                </div>
              </div>

              {/* Right Column - Preview */}
              <MarketplaceListingPreview
                title={title}
                summary={summary}
                creditBounty={data.creditBounty}
                deadline={data.deadline}
                originalClipImageUrl={data.originalClipImageUrl}
                status={data.status}
              />
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className='flex items-center justify-end gap-3 border-t border-border-primary px-6 py-4'>
          <button
            onClick={onClose}
            className='rounded-lg border border-border-primary bg-background-primary px-4 py-2 text-sm font-medium text-foreground-primary transition-colors hover:bg-background-secondary'
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={isLoading || !title.trim() || !summary.trim()}
            className='flex items-center justify-center rounded-lg border border-accent-brand bg-accent-brand px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
          >
            {isLoading ? (
              <div className='flex items-center justify-center gap-2'>
                <svg
                  className='h-4 w-4 animate-spin'
                  fill='none'
                  viewBox='0 0 24 24'
                >
                  <circle
                    className='opacity-25'
                    cx='12'
                    cy='12'
                    r='10'
                    stroke='currentColor'
                    strokeWidth='4'
                  />
                  <path
                    className='opacity-75'
                    fill='currentColor'
                    d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                  />
                </svg>
                Saving...
              </div>
            ) : (
              'Save Changes'
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default MarketplaceEditListingModal;
