'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 | null;
    effectivePrice: number;
  };
  designJson: string;
  designPreviewUrl: string;
  placementPreviewUrl: string | null;
  color: string;
  size: string | null;
  status: string;
  expectedDeliveryDate: string | null;
}

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',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });
      if (res.ok) {
        const updated = await res.json();
        setDesign(updated);

        // Add to cart
        addItem({
          cartItemId: crypto.randomUUID?.() || Math.random().toString(36).substr(2, 9),
          productId: design.productId,
          slug: design.product.id, // Using product ID as slug for now
          name: design.product.name,
          mockup: design.product.id,
          color: design.color,
          size: design.size,
          quantity: 1,
          unitPrice: design.product.personalisedPrice ?? design.product.effectivePrice,
          designJson: design.designJson,
          designPreviewUrl: design.designPreviewUrl,
          designPreviewUrlBack: design.designPreviewUrlBack,
          placementPreviewUrl: design.placementPreviewUrl,
          placementPreviewUrlBack: design.placementPreviewUrlBack,
          designWidthCm: null,
          designHeightCm: null,
        });

        alert('Design approved! Added to your bag.');
      } else {
        alert('Failed to approve design. Please try again.');
      }
    } catch (error) {
      console.error('Error approving design:', error);
      alert('An error occurred. Please try again.');
    } 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 md:items-start">
        {/* 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.personalisedPrice ?? design.product.effectivePrice) / 100).toFixed(2)}
              </p>
              {design.expectedDeliveryDate && (
                <p className="text-xs text-muted pt-2">
                  <strong>Est. delivery:</strong> {new Date(design.expectedDeliveryDate).toLocaleDateString(undefined, { dateStyle: 'medium' })}
                </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>
  );
}
