'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import DesignApprovalChat from '@/components/DesignApprovalChat';

interface DesignApproval {
  id: string;
  customerEmail: string;
  customerName: string | null;
  productId: string;
  product: {
    id: string;
    name: string;
  };
  designJson: string;
  designPreviewUrl: string;
  designPreviewUrlBack: string | null;
  placementPreviewUrl: string | null;
  placementPreviewUrlBack: string | null;
  designWidthCm: number | null;
  designHeightCm: number | null;
  color: string;
  size: string | null;
  status: string;
  createdAt: string;
}

export default function DesignDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const [design, setDesign] = useState<DesignApproval | null>(null);
  const [loading, setLoading] = useState(true);
  const [approving, setApproving] = useState(false);
  const [deleting, setDeleting] = useState(false);

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

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

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

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this design? This cannot be undone.')) return;

    setDeleting(true);
    try {
      const res = await fetch(`/api/designs/${params.id}`, { method: 'DELETE' });
      if (res.ok) {
        router.push('/admin/designs');
      } else {
        alert('Failed to delete design');
      }
    } finally {
      setDeleting(false);
    }
  };

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

      <h1 className="font-display text-3xl mb-8">{design.product.name}</h1>

      <div className="grid gap-8">
        {/* Design Preview & Editor */}
        <div className="border border-line bg-surface p-6">
          <div className="flex items-center justify-between mb-4">
            <p className="tag-label">Design Preview</p>
            {design.status === 'PENDING' && (
              <Link
                href={`/admin/designs/${params.id}/edit`}
                className="text-xs px-3 py-2 border border-clay text-clay hover:bg-clay/10 inline-block"
              >
                Open full editor →
              </Link>
            )}
          </div>

          <div className="space-y-4">
              <div>
                <p className="text-sm text-muted mb-2">Design preview (transparent)</p>
                <img
                  src={design.designPreviewUrl}
                  alt="design preview"
                  className="w-full max-w-md border border-line"
                />
              </div>

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

              {design.designPreviewUrlBack && (
                <div>
                  <p className="text-sm text-muted mb-2">Back design preview</p>
                  <img
                    src={design.designPreviewUrlBack}
                    alt="design preview back"
                    className="w-full max-w-md border border-line"
                  />
                </div>
              )}

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

        {/* Customer Details & Chat */}
        <div className="grid gap-8 md:grid-cols-2">
          <div className="border border-line bg-surface p-4">
            <p className="tag-label mb-3">Customer Details</p>
            <div className="space-y-2 text-sm">
              <p>
                <strong>Name:</strong> {design.customerName || '(not provided)'}
              </p>
              <p>
                <strong>Email:</strong> {design.customerEmail}
              </p>
              <p>
                <strong>Product:</strong> {design.product.name}
              </p>
              <p>
                <strong>Color:</strong> {design.color}
              </p>
              {design.size && (
                <p>
                  <strong>Size:</strong> {design.size}
                </p>
              )}
              {design.designWidthCm && design.designHeightCm && (
                <p>
                  <strong>Design Dimensions:</strong> {design.designWidthCm} cm × {design.designHeightCm} cm
                </p>
              )}
              <p>
                <strong>Status:</strong>{' '}
                <span
                  className={`text-xs px-2 py-1 rounded ${
                    design.status === 'PENDING'
                      ? 'bg-orange-100 text-orange-700'
                      : design.status === 'APPROVED'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-red-100 text-red-700'
                  }`}
                >
                  {design.status}
                </span>
              </p>
            </div>

            {/* Action Buttons */}
            {design.status === 'PENDING' && (
              <div className="mt-6 flex gap-3">
                <button
                  onClick={handleApprove}
                  disabled={approving}
                  className="flex-1 bg-clay px-4 py-2 text-sm font-medium text-paper hover:bg-clay-dark disabled:opacity-60"
                >
                  {approving ? 'Approving…' : 'Approve Design'}
                </button>
              </div>
            )}
            <div className="mt-4 pt-4 border-t border-line">
              <button
                onClick={handleDelete}
                disabled={deleting}
                className="w-full bg-red-600 px-4 py-2 text-sm font-medium text-paper hover:bg-red-700 disabled:opacity-60"
              >
                {deleting ? 'Deleting…' : 'Delete Design'}
              </button>
            </div>
          </div>

          {/* Chat */}
          <div>
            <DesignApprovalChat
              designId={params.id}
              role="ADMIN"
              otherPartyLabel={design.customerName || design.customerEmail}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
