'use client';

import React, { useEffect, useState } from 'react';
import { X, FileText, CheckCircle2, XCircle, Eye, Layers, Ban } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { PurchaseOrderRecord, PurchaseOrderScope } from '@/services/purchase-orders/types';
import { useAccountsReview, useCancelPurchaseOrder } from '@/services/purchase-orders/queries';
import AssignCouponsModal from './AssignCouponsModal';
import DocumentPreviewModal from '@/components/modals/DocumentPreviewModal';

const STATUS_STYLES: Record<string, string> = {
  PENDING: 'bg-amber-500/10 text-amber-500 border-amber-500/20',
  ACCOUNTS_APPROVED: 'bg-sky-500/10 text-sky-500 border-sky-500/20',
  ACCOUNTS_REJECTED: 'bg-destructive/10 text-destructive border-destructive/20',
  COUPONS_ASSIGNED: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20',
  REJECTED: 'bg-destructive/10 text-destructive border-destructive/20',
  CANCELLED: 'bg-muted/40 text-muted-foreground border-border/40',
};

interface Props {
  po: PurchaseOrderRecord;
  currentUserId?: string;
  /** Which queue this drawer was opened from — governs which action buttons render */
  scope: PurchaseOrderScope;
  onClose: () => void;
  onRefresh?: () => void;
}

export default function PurchaseOrderDrawer({ po, currentUserId, scope, onClose, onRefresh }: Props) {
  const [isMounted, setIsMounted] = useState(false);
  const [remarks, setRemarks] = useState('');
  const [showAssignModal, setShowAssignModal] = useState(false);

  // Document Preview Modal State
  const [previewTarget, setPreviewTarget] = useState<{
    name: string;
    url: string;
  } | null>(null);

  const accountsReview = useAccountsReview();
  const cancelMutation = useCancelPurchaseOrder();

  useEffect(() => {
    setIsMounted(true);
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, []);

  console.log('PurchaseOrderDrawer rendered with po:', po, 'scope:', scope, 'currentUserId:', currentUserId);

  const handleSafeClose = () => {
    setIsMounted(false);
    setTimeout(onClose, 250);
  };

  const handleReview = async (decision: 'APPROVED' | 'REJECTED') => {
    try {
      await accountsReview.mutateAsync({ id: po.id, decision, remarks: remarks.trim() || undefined });
      onRefresh?.();
      handleSafeClose();
    } catch {
      // handled by mutation toast
    }
  };

  const handleCancel = async () => {
    try {
      await cancelMutation.mutateAsync(po.id);
      onRefresh?.();
      handleSafeClose();
    } catch {
      // handled by mutation toast
    }
  };

  // Determine button permissions safely
  const canCancel = scope === 'mine' && po.status === 'PENDING' && po.createdBy.id === currentUserId;
  const canReview = scope === 'review' && po.status === 'PENDING';
  const canAssign = (scope === 'assign' || scope === 'assigned_to_me') && po.status === 'ACCOUNTS_APPROVED';
  

  return (
    <>
      <div
        className={`fixed inset-0 bg-black/40 backdrop-blur-xs z-40 transition-opacity duration-300 ${
          isMounted ? 'opacity-100' : 'opacity-0'
        }`}
        onClick={handleSafeClose}
      />

      <div
        className={`fixed right-0 top-0 bottom-0 w-full max-w-xl bg-background border-l border-border shadow-2xl z-50 p-6 flex flex-col justify-between transform transition-transform duration-300 ${
          isMounted ? 'translate-x-0' : 'translate-x-full'
        }`}
      >
        <div className="space-y-5 flex-1 overflow-y-auto pr-1">
          <div className="flex items-center justify-between border-b border-border/10 pb-4">
            <div className="flex items-center gap-2.5">
              <div className="h-9 w-9 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center">
                <FileText className="h-4 w-4 text-primary" />
              </div>
              <div>
                <h2 className="text-sm font-bold text-foreground leading-tight">{po.poNumber}</h2>
                <span className="text-[10px] text-muted-foreground font-mono">{po.type.replace(/_/g, ' → ')}</span>
              </div>
            </div>
            <button onClick={handleSafeClose} className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground/70 cursor-pointer">
              <X className="h-4 w-4" />
            </button>
          </div>

          <div className="flex items-center justify-between">
            <span
              className={`inline-flex items-center gap-1 px-2.5 py-0.5 text-[10px] font-bold rounded-full border uppercase ${
                STATUS_STYLES[po.status] || 'bg-muted/40 text-muted-foreground border-border/40'
              }`}
            >
              {po.status.replace(/_/g, ' ')}
            </span>
            <span className="text-[11px] font-bold text-foreground">{po.quantityAsked} coupon(s) requested</span>
          </div>

          <div className="bg-muted/30 border border-border/40 rounded-xl p-3.5 space-y-2 text-xs">
            <div className="flex items-center justify-between">
              <span className="text-muted-foreground/70">Raised By</span>
              <span className="font-semibold text-foreground">
                {po.createdBy.firstName} {po.createdBy.lastName} ({po.createdBy.role.replace(/_/g, ' ')})
              </span>
            </div>
            {po.neftTransactionNo && (
              <div className="flex items-center justify-between">
                <span className="text-muted-foreground/70">NEFT Reference</span>
                <span className="font-mono font-semibold text-foreground">{po.neftTransactionNo}</span>
              </div>
            )}
            {po.message && (
              <div className="pt-1 border-t border-border/10">
                <span className="text-muted-foreground/70 block mb-0.5">Notes</span>
                <span className="text-foreground">{po.message}</span>
              </div>
            )}
          </div>

          {po.documents.length > 0 && (
            <div className="space-y-2">
              <span className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Payment Proof ({po.documents.length})
              </span>
              <div className="flex flex-wrap gap-2">
                {po.documents.map((doc) => (
                  <button
                    key={doc.id || doc.fileUrl}
                    type="button"
                    onClick={() =>
                      setPreviewTarget({
                        name: doc.documentType,
                        url: doc.fileUrl,
                      })
                    }
                    className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-muted/50 hover:bg-primary/10 text-primary border border-border/40 hover:border-primary/30 transition-all text-xs font-semibold cursor-pointer group max-w-[300px]"
                    title={doc.fileName}
                  >
                    <FileText className="h-3.5 w-3.5 text-muted-foreground group-hover:text-primary shrink-0 transition-colors" />
                    <span className="font-medium text-foreground group-hover:text-primary truncate text-[11px] transition-colors">
                      {doc.fileName}
                    </span>
                    <Eye className="h-3.5 w-3.5 text-primary shrink-0 opacity-70 group-hover:opacity-100 transition-opacity" />
                  </button>
                ))}
              </div>
            </div>
          )}

          {po.accountsApprovedBy && (
            <div className="p-2.5 rounded-lg bg-muted/20 border border-border/40 text-[11px] flex items-center justify-between">
              <span className="text-muted-foreground/70">Accounts Reviewed By</span>
              <span className="font-semibold text-foreground">
                {po.accountsApprovedBy.firstName} {po.accountsApprovedBy.lastName}
              </span>
            </div>
          )}
          {po.accountsRemarks && (
            <p className="text-[11px] text-muted-foreground/70 italic">{po.accountsRemarks}</p>
          )}

          {po.allocations.length > 0 && (
            <div className="space-y-1.5">
              <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Assigned Coupons ({po.allocations.length})
              </span>
              <div className="max-h-40 overflow-y-auto space-y-1">
                {po.allocations.map((a) => (
                  <div
                    key={a.id}
                    className="flex items-center justify-between p-2 bg-background border border-border/40 rounded-lg text-[11px] font-mono"
                  >
                    <span>{a.coupon.code}</span>
                    <CheckCircle2 className="h-3 w-3 text-emerald-500" />
                  </div>
                ))}
              </div>
            </div>
          )}

          {canReview && (
            <div className="space-y-2 pt-2 border-t border-border/10">
              <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Accounts Remarks
              </label>
              <textarea
                value={remarks}
                onChange={(e) => setRemarks(e.target.value)}
                rows={2}
                placeholder="Optional remarks for approval or rejection…"
                className="w-full text-xs font-medium p-2.5 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
              />
            </div>
          )}
        </div>

        <div className="border-t border-border/10 pt-4 flex items-center justify-between gap-2">
          <Button variant="ghost" onClick={handleSafeClose} className="h-8 text-xs font-semibold cursor-pointer">
            Dismiss
          </Button>

          <div className="flex items-center gap-2">
            {canCancel && (
              <Button
                variant="outline"
                disabled={cancelMutation.isPending}
                onClick={handleCancel}
                className="h-8 text-[11px] font-bold rounded-lg border-destructive/20 text-destructive hover:bg-destructive/10 gap-1 cursor-pointer"
              >
                <Ban className="h-3.5 w-3.5" /> Cancel Order
              </Button>
            )}

            {canReview && (
              <>
                <Button
                  variant="outline"
                  disabled={accountsReview.isPending}
                  onClick={() => handleReview('REJECTED')}
                  className="h-8 text-[11px] font-bold rounded-lg border-destructive/20 text-destructive hover:bg-destructive/10 gap-1 cursor-pointer"
                >
                  <XCircle className="h-3.5 w-3.5" /> Reject
                </Button>
                <Button
                  disabled={accountsReview.isPending}
                  onClick={() => handleReview('APPROVED')}
                  className="h-8 text-[11px] font-bold rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white gap-1 cursor-pointer"
                >
                  <CheckCircle2 className="h-3.5 w-3.5" /> Approve Payment
                </Button>
              </>
            )}

            {canAssign && (
              <Button
                onClick={() => setShowAssignModal(true)}
                className="h-8 text-[11px] font-bold rounded-lg bg-foreground text-background hover:bg-foreground/90 gap-1 cursor-pointer"
              >
                <Layers className="h-3.5 w-3.5" /> Assign Coupons
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* Document Preview Modal */}
      {previewTarget && (
        <DocumentPreviewModal
          documentName={previewTarget.name}
          fileUrl={previewTarget.url}
          onClose={() => setPreviewTarget(null)}
        />
      )}

      {showAssignModal && (
        <AssignCouponsModal
          po={po}
          onClose={() => {
            setShowAssignModal(false);
            onRefresh?.();
            handleSafeClose();
          }}
        />
      )}
    </>
  );
}