'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useCart } from '@/lib/cartStore';

interface DesignApproval {
  id: string;
  customerEmail: string;
  customerName: string | null;
  productId: string;
  product: {
    id: string;
    name: string;
    basePrice: number;
    personalisedPrice: number;
    effectivePrice: number;
  };
  designJson: string;
  designPreviewUrl: string;
  placementPreviewUrl: string | null;
  color: string;
  size: string | null;
  status: string;
}

export default function DesignReviewPage({ params }: { params: { id: string } }) {
  const [design, setDesign] = useState<DesignApproval | null>(null);
  const [loading, setLoading] = useState(true);
  const [approving, setApproving] = useState(false);
  const [changingMessage, setChangingMessage] = useState('');
  const [sendingChanges, setSendingChanges] = useState(false);
  const addItem = useCart((s) => s.addItem);

  useEffect(() => {
    fetch(`/api/designs/${params.id}`)
      .then((r) => r.json())
      .then(setDesign)
      .finally(() => setLoading(false));
  }, [params.id]);

  const handleApprove = async () => {
    if (!design) return;
    setApproving(true);
    try {
      const res = await fetch(`/api/designs/${params.id}/approve`, { method: 'POST' });
      if (res.ok) {
        const updated = await res.json();
        setDesign(updated);

        // Add to cart
        addItem({
          productId: design.productId,
          color: design.color,
          size: design.size,
          designJson: design.designJson,
          quantity: 1,
        });

        alert('Design approved! Added to your bag.');
      }
    } finally {
      setApproving(false);
    }
  };

  const handleRequestChanges = async () => {
    if (!changingMessage.trim()) {
      alert('Please provide feedback for the design changes');
      return;
    }

    setSendingChanges(true);
    try {
      const res = await fetch(`/api/designs/${params.id}/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: changingMessage,
          role: 'CUSTOMER',
          messageType: 'CHANGE_REQUEST',
        }),
      });

      if (res.ok) {
        // Update status back to PENDING so admin can see it
        await fetch(`/api/designs/${params.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: 'PENDING' }),
        });

        alert('Changes requested! The admin has been notified.');
        setChangingMessage('');
        // Reload design
        const updated = await fetch(`/api/designs/${params.id}`).then((r) => r.json());
        setDesign(updated);
      }
    } finally {
      setSendingChanges(false);
    }
  };

  if (loading) return <div className="p-6">Loading...</div>;
  if (!design) return <div className="p-6 text-sm text-muted">Design not found.</div>;

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <Link href="/" className="text-sm text-clay hover:text-clay-dark mb-6 inline-block">
        ← Back to shop
      </Link>

      <h1 className="font-display text-3xl mb-2">{design.product.name}</h1>
      <p className="text-muted mb-8">Review your personalized design</p>

      <div className="grid gap-8 md:grid-cols-2">
        {/* Design Preview */}
        <div className="space-y-4">
          <div>
            <p className="text-sm text-muted mb-2">Design preview</p>
            <img
              src={design.designPreviewUrl}
              alt="design preview"
              className="w-full border border-line"
            />
          </div>

          {design.placementPreviewUrl && (
            <div>
              <p className="text-sm text-muted mb-2">Design on product</p>
              <img
                src={design.placementPreviewUrl}
                alt="placement preview"
                className="w-full border border-line"
              />
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="space-y-6">
          <div className="border border-line bg-surface p-6">
            <p className="tag-label mb-4">Order Summary</p>
            <div className="space-y-3 text-sm mb-6">
              <p>
                <strong>Product:</strong> {design.product.name}
              </p>
              <p>
                <strong>Color:</strong> {design.color}
              </p>
              {design.size && (
                <p>
                  <strong>Size:</strong> {design.size}
                </p>
              )}
              <p className="border-t border-line pt-3">
                <strong>Price:</strong> £{(design.product.effectivePrice / 100).toFixed(2)}
              </p>
            </div>

            <button
              onClick={handleApprove}
              disabled={approving}
              className="w-full bg-clay px-4 py-3 text-sm font-medium text-paper hover:bg-clay-dark disabled:opacity-60 mb-3"
            >
              {approving ? 'Processing…' : 'Approve & Add to Bag'}
            </button>
          </div>

          {/* Request Changes */}
          <div className="border border-line bg-surface p-6">
            <p className="tag-label mb-4">Request Changes</p>
            <textarea
              value={changingMessage}
              onChange={(e) => setChangingMessage(e.target.value)}
              placeholder="Describe what you'd like to change..."
              className="w-full border border-line bg-paper px-3 py-2 text-sm mb-3 min-h-24"
            />
            <button
              onClick={handleRequestChanges}
              disabled={sendingChanges || !changingMessage.trim()}
              className="w-full border border-ink px-4 py-3 text-sm font-medium text-ink hover:border-clay hover:bg-clay hover:text-paper disabled:opacity-60"
            >
              {sendingChanges ? 'Sending…' : 'Send Changes to Admin'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
