
/* eslint-disable -- temporary disable for development/testing purposes */

'use client';

import { useState, useEffect } from 'react';
import {
  Box, Card, Divider, Typography,
  Tabs, Tab, Table, TableBody, TableCell,
  TableContainer, TableHead, TableRow, Paper
} from '@mui/material';
import { useParams } from 'next/navigation'; // ✅ Import useParams

export default function CompanyDetailsPage() {
  const [tab, setTab] = useState(0);
  const [companyData, setCompanyData] = useState<any>(null); // State for company details
  const [companyUsers, setCompanyUsers] = useState<any>(null); // State for company users
  const [loading, setLoading] = useState(true);
  // const [error, setError] = useState<string | null>(null);
 

  const params = useParams(); // ✅ Get route parameters
  const companyId = params?.id; // ✅ Extract ID from URL

  const handleChange = (_: React.SyntheticEvent, newValue: number) => {
    setTab(newValue);
  };

  useEffect(() => {
    const fetchCompanyData = async () => {
      if (!companyId) return;

      try {
        const companyResponse = await fetch(`/api/companies/${companyId}`);
        if (!companyResponse.ok) {
          throw new Error('Failed to fetch company details');
        }
        const companyDetails = await companyResponse.json();
        // console.log(companyDetails, 'fetched company details');
        setCompanyData(companyDetails[0]);

        const response = await fetch(`/api/companies/${companyId}/users`);
        const usersData = await response.json();
        // console.log(usersData, 'fetched company data');
        setCompanyUsers(usersData);
      } catch (error) {
        // console.error('Error fetching company users:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchCompanyData();
  }, [companyId]);

  const renderUserTable = (data: any[]) => (
    <TableContainer component={Paper}>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Name</TableCell>
            <TableCell>Email</TableCell>
            <TableCell>Phone</TableCell>
            <TableCell>Role</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map((user) => (
            <TableRow key={user.id}>
              <TableCell>{user.name}</TableCell>
              <TableCell>{user.email}</TableCell>
              <TableCell>{user.mobile_number}</TableCell> {/* Updated key */}
              <TableCell>{user.role}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );

  if (loading) {
    return <Typography>Loading...</Typography>;
  }

  return (
    <Box p={4}>
      {/* Company Details */}
      {/* Company Details */}
      {companyData && (
      <Card sx={{ p: 3, mb: 4 }}>
        <Typography variant="h5">{companyData.first_name}</Typography>
        <Typography>Email: {companyData.email}</Typography>
        <Typography>Phone: {companyData.mobile_number}</Typography>
        <Typography>
          Address: {companyData.address}
        </Typography>
      </Card>
)}

      {/* Tabs */}
      <Tabs value={tab} onChange={handleChange}>
        <Tab label={`Managers (${companyUsers?.managers?.length || 0})`} />
        <Tab label={`Providers (${companyUsers?.providers?.length || 0})`} />
        <Tab label={`Patients (${companyUsers?.patients?.length || 0})`} />
      </Tabs>
      <Divider sx={{ my: 2 }} />

      {/* Tab Content */}
      {tab === 0 && (
        <Box>
          <Typography variant="h6" mb={2}>Managers</Typography>
          {companyUsers?.managers && renderUserTable(companyUsers.managers)}
        </Box>
      )}
      {tab === 1 && (
        <Box>
          <Typography variant="h6" mb={2}>Providers</Typography>
          {companyUsers?.providers && renderUserTable(companyUsers.providers)}
        </Box>
      )}
      {tab === 2 && (
        <Box>
          <Typography variant="h6" mb={2}>Patients</Typography>
          {companyUsers?.patients && renderUserTable(companyUsers.patients)}
        </Box>
      )}
    </Box>
  );
}
