import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head';
import { mdiShieldCheck, mdiCheck, mdiClose, mdiEye } from '@mdi/js';
import axios from 'axios';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseIcon from '../../components/BaseIcon';
import LoadingSpinner from '../../components/LoadingSpinner';
import { getPageTitle } from '../../config';

const ClaimRequestsListPage = () => {
  const [loading, setLoading] = useState(true);
  const [requests, setRequests] = useState<any[]>([]);

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

  const fetchRequests = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/claim_requests');
      setRequests(response.data.rows);
    } catch (error) {
      console.error('Error fetching claim requests:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAction = async (id: string, status: string) => {
    let rejectionReason = '';
    if (status === 'REJECTED') {
      rejectionReason = prompt('Please enter rejection reason:') || 'Documentation insufficient';
    }
    try {
      await axios.put(`/claim_requests/${id}`, { data: { status, rejectionReason } });
      fetchRequests();
    } catch (error) {
      console.error('Error updating claim request:', error);
      alert('Failed to update request.');
    }
  };

  if (loading) return <SectionMain><LoadingSpinner /></SectionMain>;

  return (
    <>
      <Head>
        <title>{getPageTitle('Claim Requests')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiShieldCheck} title="Claim Requests" main />

        <CardBox className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="p-4 font-bold text-slate-500 uppercase text-xs">Business</th>
                <th className="p-4 font-bold text-slate-500 uppercase text-xs">User</th>
                <th className="p-4 font-bold text-slate-500 uppercase text-xs">Status</th>
                <th className="p-4 font-bold text-slate-500 uppercase text-xs">Date</th>
                <th className="p-4 font-bold text-slate-500 uppercase text-xs text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {requests.map((request) => (
                <tr key={request.id} className="border-b border-slate-50 hover:bg-slate-50 transition-colors">
                  <td className="p-4">
                    <div className="font-bold">{request.business?.name}</div>
                    <div className="text-xs text-slate-400">{request.business?.city}, {request.business?.state}</div>
                  </td>
                  <td className="p-4">
                    <div className="font-medium">{request.user?.firstName} {request.user?.lastName}</div>
                    <div className="text-xs text-slate-400">{request.user?.email}</div>
                  </td>
                  <td className="p-4">
                    <span className={`px-2 py-1 rounded-full text-[10px] font-bold uppercase ${
                      request.status === 'APPROVED' ? 'bg-emerald-50 text-emerald-600' : 
                      request.status === 'REJECTED' ? 'bg-rose-50 text-rose-600' : 
                      'bg-amber-50 text-amber-600'
                    }`}>
                      {request.status}
                    </span>
                  </td>
                  <td className="p-4 text-sm text-slate-500">
                    {new Date(request.createdAt).toLocaleDateString()}
                  </td>
                  <td className="p-4 text-right">
                    <div className="flex justify-end gap-2">
                       <BaseButton 
                          icon={mdiEye} 
                          color="info" 
                          small 
                          href={`/public/businesses-details?id=${request.businessId}`}
                          target="_blank"
                       />
                       {request.status === 'PENDING' && (
                         <>
                           <BaseButton 
                              icon={mdiCheck} 
                              color="success" 
                              small 
                              onClick={() => handleAction(request.id, 'APPROVED')} 
                            />
                           <BaseButton 
                              icon={mdiClose} 
                              color="danger" 
                              small 
                              onClick={() => handleAction(request.id, 'REJECTED')} 
                            />
                         </>
                       )}
                    </div>
                  </td>
                </tr>
              ))}
              {requests.length === 0 && (
                <tr>
                  <td colSpan={5} className="p-10 text-center text-slate-400 italic">No claim requests found.</td>
                </tr>
              )}
            </tbody>
          </table>
        </CardBox>
      </SectionMain>
    </>
  );
};

ClaimRequestsListPage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission="READ_CLAIM_REQUESTS">
      {page}
    </LayoutAuthenticated>
  );
};

export default ClaimRequestsListPage;
