import React, { useState } from "react";
import { conditionCheckAPI } from "../services/api";
import { uploadImagesWithVariants } from "../services/uploadService";
import { IMAGE_LIMITS } from "../config/imageLimits";

interface ConditionCheckModalProps {
  show: boolean;
  onHide: () => void;
  rentalId: string;
  checkType: string;
  itemName: string;
  onSuccess: () => void;
}

const ConditionCheckModal: React.FC<ConditionCheckModalProps> = ({
  show,
  onHide,
  rentalId,
  checkType,
  itemName,
  onSuccess,
}) => {
  const [photos, setPhotos] = useState<File[]>([]);
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const getCheckTypeInfo = () => {
    const types = {
      pre_rental_owner: {
        title: "Pre-Rental Condition",
        description:
          "Document the current condition of your item before the rental begins. Take clear photos showing all sides and any existing wear or damage",
      },
      rental_start_renter: {
        title: "Rental Start Condition",
        description:
          "Document the condition of the item when you receive it. Take photos of any damage or issues you notice upon receiving the item",
      },
      rental_end_renter: {
        title: "Rental End Condition",
        description:
          "Document the condition of the item before returning it. Take photos showing the item's condition before you return it",
      },
      post_rental_owner: {
        title: "Post-Rental Condition",
        description:
          "Document the condition of your item after it's been returned. Take photos of the returned item including any damage or issues",
      },
    };
    return (
      types[checkType as keyof typeof types] || {
        title: "Condition Check",
        description: "Document the item's condition",
      }
    );
  };

  const typeInfo = getCheckTypeInfo();

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const selectedFiles = Array.from(e.target.files);
      if (selectedFiles.length + photos.length > IMAGE_LIMITS.conditionChecks) {
        setError(`Maximum ${IMAGE_LIMITS.conditionChecks} photos allowed`);
        return;
      }
      setPhotos((prev) => [...prev, ...selectedFiles]);
      setError(null);
    }
  };

  const removePhoto = (index: number) => {
    setPhotos((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    if (photos.length === 0) {
      setError("Please upload at least one photo");
      return;
    }

    try {
      setSubmitting(true);
      setError(null);

      // Upload photos to S3 first (with resizing)
      const uploadResults = await uploadImagesWithVariants(
        "condition-check",
        photos
      );
      const imageFilenames = uploadResults.map((result) => result.baseKey);

      // Submit condition check with S3 keys
      await conditionCheckAPI.submitConditionCheck(rentalId, {
        checkType,
        imageFilenames,
        notes: notes.trim() || undefined,
      });

      // Reset form
      setPhotos([]);
      setNotes("");
      onSuccess();
      onHide();
    } catch (error: any) {
      setError(
        error.response?.data?.error || "Failed to submit condition check"
      );
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    setPhotos([]);
    setNotes("");
    setError(null);
    onHide();
  };

  if (!show) return null;

  return (
    <div
      className="modal show d-block"
      tabIndex={-1}
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
    >
      <div className="modal-dialog modal-lg">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              <i className="bi bi-camera me-2" />
              {typeInfo.title}
            </h5>
            <button
              type="button"
              className="btn-close"
              onClick={handleClose}
              disabled={submitting}
            />
          </div>

          <div className="modal-body">
            <div className="mb-4">
              <h6 className="text-center text-dark">{itemName}</h6>
              <p className="text-muted mb-2">{typeInfo.description}</p>
            </div>

            {error && (
              <div className="alert alert-danger" role="alert">
                {error}
              </div>
            )}

            <div className="mb-3">
              <label className="form-label">
                Photos <span className="text-danger">*</span>
                <small className="text-muted ms-2">
                  (Maximum {IMAGE_LIMITS.conditionChecks} photos)
                </small>
              </label>
              <input
                type="file"
                className="form-control"
                multiple
                accept="image/*"
                onChange={handleFileChange}
                disabled={submitting}
              />
            </div>

            {photos.length > 0 && (
              <div className="mb-3">
                <label className="form-label">
                  Selected Photos ({photos.length})
                </label>
                <div className="row">
                  {photos.map((photo, index) => (
                    <div key={index} className="col-md-3 mb-2">
                      <div className="position-relative">
                        <img
                          src={URL.createObjectURL(photo)}
                          alt={`Photo ${index + 1}`}
                          className="img-fluid rounded"
                          style={{
                            maxHeight: "120px",
                            objectFit: "contain",
                            width: "100%",
                          }}
                        />
                        <button
                          type="button"
                          className="btn btn-danger btn-sm position-absolute top-0 end-0"
                          onClick={() => removePhoto(index)}
                          disabled={submitting}
                          style={{ transform: "translate(50%, -50%)" }}
                        >
                          <i className="bi bi-x" />
                        </button>
                      </div>
                      <small className="text-muted d-block text-center mt-1">
                        {photo.name.length > 15
                          ? `${photo.name.substring(0, 15)}...`
                          : photo.name}
                      </small>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className="mb-3">
              <label className="form-label">Notes (Optional)</label>
              <textarea
                className="form-control"
                rows={3}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Add any additional notes about the item's condition"
                maxLength={500}
                disabled={submitting}
              />
              <div className="form-text">{notes.length}/500 characters</div>
            </div>
          </div>

          <div className="modal-footer">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={handleClose}
              disabled={submitting}
            >
              Cancel
            </button>
            <button
              type="button"
              className="btn btn-primary"
              onClick={handleSubmit}
              disabled={submitting || photos.length === 0}
            >
              {submitting ? (
                <>
                  <div
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                  >
                    <span className="visually-hidden">Loading...</span>
                  </div>
                  Submitting...
                </>
              ) : (
                <>Submit Condition Check</>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConditionCheckModal;
