import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { Organization, ResourceFlow } from '@/types.ts';
import Button from '@/components/ui/Button.tsx';
import Textarea from '@/components/ui/Textarea.tsx';
import Wizard from '@/components/wizard/Wizard.tsx';

interface ProposalModalContext {
  targetOrg: Organization;
  resource: ResourceFlow;
  resourceType: 'input' | 'output';
}

interface CreateProposalModalProps {
  isOpen: boolean;
  onClose: () => void;
  context: ProposalModalContext | null;
  onSubmit: (message: string) => void;
}

const CreateProposalModal = ({ isOpen, onClose, context, onSubmit }: CreateProposalModalProps) => {
  const { t } = useTranslation();
  const [message, setMessage] = useState('');

  // Reset message when modal opens to clear any previous input
  useEffect(() => {
    if (isOpen) {
      setMessage(''); // eslint-disable-line
    }
  }, [isOpen]);

  const handleSubmit = useCallback(
    (e: React.FormEvent) => {
      e.preventDefault();
      onSubmit(message);
    },
    [message, onSubmit]
  );

  if (!context) return null;

  const { targetOrg, resource, resourceType } = context;

  return (
    <Wizard isOpen={isOpen} onClose={onClose} title={t('organizationPage.proposalModal.title')}>
      <form onSubmit={handleSubmit}>
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium text-muted-foreground">
              {t('organizationPage.proposalModal.to')}
            </label>
            <p className="font-semibold text-lg">{targetOrg.Name}</p>
          </div>
          <div>
            <p className="text-sm text-muted-foreground">
              {t(
                resourceType === 'input'
                  ? 'organizationPage.proposalModal.offeringToFulfill'
                  : 'organizationPage.proposalModal.requestingToFulfill'
              )}
            </p>
            <p className="font-semibold text-primary text-lg">&ldquo;{resource.Type}&rdquo;</p>
          </div>
          <div>
            <label htmlFor="proposal-message" className="text-sm font-medium">
              {t('organizationPage.proposalModal.messageLabel')}
            </label>
            <Textarea
              id="proposal-message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder={t('organizationPage.proposalModal.messagePlaceholder')}
              rows={4}
              className="mt-1"
            />
          </div>
        </div>
        <footer className="mt-6 flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={onClose}>
            {t('organizationPage.proposalModal.cancelButton')}
          </Button>
          <Button type="submit">{t('organizationPage.proposalModal.sendButton')}</Button>
        </footer>
      </form>
    </Wizard>
  );
};

export default React.memo(CreateProposalModal);
