'use client';

import { useState } from 'react';
import { AttachmentUploader } from '@/components/messaging/attachment-uploader';
import { useRequestReturn } from '@/lib/queries/use-returns';
import type { OrderItemData, ReturnReason } from '@alqove/api-client';

interface Props {
  orderId: string;
  items: OrderItemData[];
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

const REASONS: { value: ReturnReason; label: string }[] = [
  { value: 'damaged', label: 'Item arrived damaged' },
  { value: 'wrong_item', label: 'Wrong item received' },
  { value: 'not_as_described', label: 'Not as described' },
  { value: 'doesnt_fit', label: "Doesn't fit" },
  { value: 'changed_mind', label: 'Changed my mind' },
  { value: 'other', label: 'Other' },
];

export function ReturnRequestModal({ orderId, items, open, onClose, onSuccess }: Props) {
  const [selected, setSelected] = useState<Set<string>>(() => new Set(items.map((i) => i.id)));
  const [reason, setReason] = useState<ReturnReason | ''>('');
  const [reasonText, setReasonText] = useState('');
  const [attachmentIds, setAttachmentIds] = useState<string[]>([]);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const requestReturn = useRequestReturn(orderId);

  if (!open) return null;

  const toggleItem = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const reasonOk = reason !== '' && (reason !== 'other' || reasonText.trim().length > 0);
  const canSubmit = selected.size > 0 && reasonOk && !requestReturn.isPending;

  const handleSubmit = async () => {
    if (!reason) return;
    setSubmitError(null);
    try {
      await requestReturn.mutateAsync({
        reason,
        reason_text: reasonText.trim() || undefined,
        item_ids: Array.from(selected),
        attachment_ids: attachmentIds.length > 0 ? attachmentIds : undefined,
      });
      onSuccess?.();
      onClose();
    } catch (e) {
      setSubmitError((e as Error).message ?? 'Failed to file return.');
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Request a return"
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
    >
      <div className="w-full max-w-lg rounded-lg bg-white p-6 shadow-xl">
        <div className="flex items-start justify-between">
          <h2 className="text-lg font-semibold text-slate-900">Request a return</h2>
          <button type="button" onClick={onClose} className="text-slate-400 hover:text-slate-600">
            <span aria-hidden>×</span>
            <span className="sr-only">Close</span>
          </button>
        </div>

        <div className="mt-4 space-y-4">
          <fieldset>
            <legend className="text-sm font-medium text-slate-700">Items to return</legend>
            <ul className="mt-2 space-y-2">
              {items.map((item) => (
                <li key={item.id}>
                  <label className="flex items-center gap-3 text-sm text-slate-800">
                    <input
                      type="checkbox"
                      checked={selected.has(item.id)}
                      onChange={() => toggleItem(item.id)}
                      className="h-4 w-4 rounded border-slate-300"
                    />
                    <span className="flex-1">{item.title_snapshot}</span>
                    <span className="text-slate-500">${(item.price_snapshot / 100).toFixed(2)}</span>
                  </label>
                </li>
              ))}
            </ul>
          </fieldset>

          <fieldset>
            <legend className="text-sm font-medium text-slate-700">Reason</legend>
            <div className="mt-2 space-y-1">
              {REASONS.map((r) => (
                <label key={r.value} className="flex items-center gap-2 text-sm text-slate-800">
                  <input
                    type="radio"
                    name="reason"
                    value={r.value}
                    checked={reason === r.value}
                    onChange={() => setReason(r.value)}
                  />
                  {r.label}
                </label>
              ))}
            </div>
          </fieldset>

          <div>
            <label htmlFor="reason_text" className="text-sm font-medium text-slate-700">
              Tell us more {reason === 'other' && <span className="text-red-500">*</span>}
            </label>
            <textarea
              id="reason_text"
              value={reasonText}
              onChange={(e) => setReasonText(e.target.value)}
              maxLength={2000}
              rows={3}
              className="mt-1 block w-full rounded-md border border-slate-300 p-2 text-sm"
              required={reason === 'other'}
            />
          </div>

          <div>
            <span className="text-sm font-medium text-slate-700">Photos (optional, up to 4)</span>
            <div className="mt-1">
              <AttachmentUploader orderId={orderId} onChange={setAttachmentIds} />
            </div>
          </div>

          {submitError && <div className="text-sm text-red-600">{submitError}</div>}
        </div>

        <div className="mt-6 flex items-center justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded-md border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={!canSubmit}
            className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {requestReturn.isPending ? 'Filing…' : 'File return'}
          </button>
        </div>
      </div>
    </div>
  );
}
