import React, { useState, useEffect } from 'react';
import { FaTrash, FaCheckCircle, FaTimesCircle, FaClock, FaChevronRight } from 'react-icons/fa';

interface DeleteRequest {
  name: string;
  target_doctype: string;
  target_name: string;
  target_display: string;
  reason: string;
  department: string;
  requested_by: string;
  workflow_state: string;
  creation: string;
}

const STATE_COLORS: Record<string, string> = {
  'Pending Supervisor': 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300',
  'Pending Cluster Manager': 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300',
  'Approved': 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300',
  'Rejected': 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300',
};

const DOCTYPE_LABELS: Record<string, string> = {
  Work_Order: 'Work Order',
  Asset: 'Asset',
  'Maintenance Schedule': 'PPM',
  'Stock Entry': 'Inventory',
};

const DeleteRequestsPage: React.FC = () => {
  const [requests, setRequests] = useState<DeleteRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [filterState, setFilterState] = useState('');
  const [userRole, setUserRole] = useState<'supervisor' | 'cluster_manager' | 'other'>('other');

  // Detect user role to show relevant actions
  useEffect(() => {
    const detectRole = async () => {
      const cmRes = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ roles: 'Cluster Manager' })
      });
      const cmData = await cmRes.json();
      if (cmData.message?.has_role) { setUserRole('cluster_manager'); return; }

      const supRes = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ roles: 'Contractor Supervisor' })
      });
      const supData = await supRes.json();
      if (supData.message?.has_role) setUserRole('supervisor');
    };
    detectRole();
  }, []);

  const fetchRequests = async () => {
    setLoading(true);
    try {
      const filters: any = {};
      if (filterState) filters['workflow_state'] = filterState;

      const res = await fetch('/api/method/frappe.client.get_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          doctype: 'Delete Request',
          filters,
          fields: [
            'name', 'target_doctype', 'target_name', 'target_display',
            'reason', 'department', 'requested_by', 'workflow_state', 'creation'
          ],
          order_by: 'creation desc',
          limit_page_length: 100
        })
      });
      const data = await res.json();
      setRequests(data.message || []);
    } catch (err) {
      console.error('Failed to fetch delete requests', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchRequests(); }, [filterState]);

  const applyAction = async (requestName: string, action: string) => {
    setActionLoading(requestName + action);
    try {
      // First get the full doc
      const docRes = await fetch('/api/method/frappe.client.get', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ doctype: 'Delete Request', name: requestName })
      });
      const docData = await docRes.json();

      // Apply workflow action
      const res = await fetch('/api/method/frappe.model.workflow.apply_workflow', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ doc: docData.message, action })
      });
      const result = await res.json();
      if (result.exc) throw new Error(result.exc);

      alert(`Action "${action}" applied successfully.`);
      fetchRequests();
    } catch (err) {
      alert(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setActionLoading(null);
    }
  };

  // What actions can the current user take on a given request
  const getAvailableActions = (req: DeleteRequest) => {
    if (userRole === 'supervisor' && req.workflow_state === 'Pending Supervisor') {
      return [
        { label: 'Forward to Cluster Manager', action: 'Send For Approval', color: 'bg-blue-600 hover:bg-blue-700' },
      ];
    }
    if (userRole === 'cluster_manager' && req.workflow_state === 'Pending Cluster Manager') {
      return [
        { label: 'Approve & Delete', action: 'Approve', color: 'bg-green-600 hover:bg-green-700' },
        { label: 'Reject', action: 'Reject', color: 'bg-red-600 hover:bg-red-700' },
      ];
    }
    return [];
  };

  const pendingCount = requests.filter(r =>
    r.workflow_state === 'Pending Supervisor' || r.workflow_state === 'Pending Cluster Manager'
  ).length;

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-800 dark:text-white flex items-center gap-3">
            <FaTrash className="text-red-500" />
            Deletion Requests
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {pendingCount > 0
              ? <span className="text-orange-600 font-medium">{pendingCount} pending your review</span>
              : 'No pending requests'}
          </p>
        </div>

        {/* Filter */}
        <select
          value={filterState}
          onChange={(e) => setFilterState(e.target.value)}
          className="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
        >
          <option value="">All Statuses</option>
          <option value="Pending Supervisor">Pending Supervisor</option>
          <option value="Pending Cluster Manager">Pending Cluster Manager</option>
          <option value="Approved">Approved</option>
          <option value="Rejected">Rejected</option>
        </select>
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-red-500"></div>
          </div>
        ) : requests.length === 0 ? (
          <div className="text-center py-20 text-gray-400">
            <FaTrash className="text-5xl mx-auto mb-3 opacity-30" />
            <p>No deletion requests found</p>
          </div>
        ) : (
          <table className="w-full">
            <thead className="bg-gray-100 dark:bg-gray-700">
              <tr>
                {['Request ID', 'Type', 'Record', 'Department', 'Requested By', 'Reason', 'Status', 'Date', 'Actions'].map(h => (
                  <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {requests.map((req) => {
                const actions = getAvailableActions(req);
                const isActing = actionLoading?.startsWith(req.name);
                return (
                  <tr key={req.name} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                    <td className="px-4 py-3 text-xs font-mono text-gray-600 dark:text-gray-400">
                      {req.name}
                    </td>
                    <td className="px-4 py-3">
                      <span className="px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded text-xs font-medium">
                        {DOCTYPE_LABELS[req.target_doctype] || req.target_doctype}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                      {req.target_display || req.target_name}
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">
                      {req.department || '-'}
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">
                      {req.requested_by}
                    </td>
                    <td className="px-4 py-3 max-w-xs">
                      <p className="text-sm text-gray-700 dark:text-gray-300 truncate" title={req.reason}>
                        {req.reason}
                      </p>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-semibold ${STATE_COLORS[req.workflow_state] || 'bg-gray-100 text-gray-700'}`}>
                        {req.workflow_state}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
                      {new Date(req.creation).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-2">
                        {actions.length > 0 ? actions.map(({ label, action, color }) => (
                          <button
                            key={action}
                            onClick={() => applyAction(req.name, action)}
                            disabled={!!isActing}
                            className={`px-3 py-1.5 text-xs font-medium text-white rounded-lg transition-colors ${color} disabled:opacity-50 disabled:cursor-not-allowed`}
                          >
                            {isActing ? '...' : label}
                          </button>
                        )) : (
                          <span className="text-xs text-gray-400 italic">No actions</span>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

export default DeleteRequestsPage;