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

'use client';

import * as React from 'react';
import { useEffect, useState } from 'react';
import type { Metadata } from 'next';
import { useRouter } from 'next/navigation';

import {
  Stack,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Input,
} from '@mui/material';

import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';

import { config } from '@/config';
 
import type { Customer } from '@/components/dashboard/customer/customers-table';

export const metadata = {
  title: `Customers | Dashboard | ${config.site.name}`
} satisfies Metadata;

interface CompanyFormData {
  first_name: string;
  last_name: string;
  email: string;
  address: string;
  mobile_number: string;
  lat: string;
  lng: string;
  profile: File | null;
  unique_id: string;
  disable: string;
}

export function ProviderPageClient(): React.JSX.Element {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);

  const [formData, setFormData] = useState<CompanyFormData>({
    first_name: '',
    last_name: '',
    email: '',
    address: '',
    mobile_number: '',
    lat: '',
    lng: '',
    profile: null,
    unique_id: '',
    disable: '0',
  });

  const page = 0;
  const rowsPerPage = 5;
  const router = useRouter();

  useEffect(() => {
    const fetchCustomers = async () => {
      try {
        const res = await fetch('/api/companies');
        const data = await res.json();
        const formatted = data.map((item: any, index: number) => ({
          ...item,
          id: item.id || `DB-USER-${index + 1}`,
          avatar: item.profile
            ? `https://helloprovider.co/app/images/${item.profile}`
            : '/assets/avatar-1.png',
          createdAt: new Date(item.createdAt || Date.now()),
        }));
        setCustomers(formatted);
      } catch (err) {
        // console.error('Failed to fetch customers', err);
      } finally {
        setLoading(false);
      }
    };

    fetchCustomers();
  }, []);

  // const handleRowClick = (id: string) => {
  //   router.push(`/dashboard/companies/${id}`);
  // };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));

    // Geocode address
    if (name === 'address' && value.trim() !== '') {
      geocodeAddress(value.trim());
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setFormData(prev => ({ ...prev, profile: e.target.files![0] }));
    }
  };

  const geocodeAddress = async (address: string) => {
    try {
      const apiKey = 'AIzaSyA2Z3ZILsy__dA15dmEJ-A5QCE-_FxY92k';
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`
      );
      const data = await response.json();

      if (data.status === 'OK') {
        const location = data.results[0].geometry.location;
        setFormData(prev => ({
          ...prev,
          lat: location.lat.toString(),
          lng: location.lng.toString(),
        }));
      } else {
        // console.warn('Geocoding failed:', data.status);
      }
    } catch (error) {
      // console.error('Geocoding error:', error);
    }
  };

  const handleAddCompany = async () => {
    try {
      const form = new FormData();
      for (const key in formData) {
        if (formData[key as keyof CompanyFormData] instanceof File) {
          form.append(key, formData[key as keyof CompanyFormData] as File);
        } else {
          form.append(key, formData[key as keyof CompanyFormData] as string);
        }
      }

      const res = await fetch('/api/companies', {
        method: 'POST',
        body: form,
      });

      if (!res.ok) throw new Error('Failed to add company');
      const newCompany = await res.json();
      setCustomers(prev => [...prev, newCompany]);
      handleClose();
    } catch (err) {
      // console.error(err);
      alert('Error adding company');
    }
  };

  const handleClose = () => {
    setOpen(false);
    setFormData({
      first_name: '',
      last_name: '',
      email: '',
      address: '',
      mobile_number: '',
      lat: '',
      lng: '',
      profile: null,
      unique_id: '',
      disable: '0',
    });
  };

  const paginatedCustomers = applyPagination(customers, page, rowsPerPage);

  return (
    <Stack spacing={3}>
      <Stack direction="row" spacing={3}>
        <Stack spacing={1} sx={{ flex: '1 1 auto' }}>
          <Typography variant="h4">Companies</Typography>
        </Stack>
        <div>
          <Button
            startIcon={<PlusIcon fontSize="var(--icon-fontSize-md)" />}
            variant="contained"
            onClick={() => setOpen(true)}
          >
            Add
          </Button>
        </div>
      </Stack>

      {/* <CustomersFilters /> */}

      {loading ? (
        <Typography>Loading companies...</Typography>
      ) : (
        <Typography>Loading companies...</Typography>

        // <CustomersTable
        //   count={customers.length}
        //   page={page}
        //   rows={paginatedCustomers}
        //   rowsPerPage={rowsPerPage}
        //   onRowClick={handleRowClick}
        // />
      )}

      <Dialog open={open} onClose={handleClose} fullWidth>
        <DialogTitle>Add New Company</DialogTitle>
        <DialogContent>
          <Stack spacing={2} mt={1}>
            <TextField label="First Name" name="first_name" value={formData.first_name} onChange={handleChange} fullWidth />
            <TextField label="Last Name" name="last_name" value={formData.last_name} onChange={handleChange} fullWidth />
            <TextField label="Email" name="email" value={formData.email} onChange={handleChange} fullWidth />
            <TextField label="Address" name="address" value={formData.address} onChange={handleChange} fullWidth />
            <TextField label="Mobile Number" name="mobile_number" value={formData.mobile_number} onChange={handleChange} fullWidth />
            <TextField label="Unique ID" name="unique_id" value={formData.unique_id} onChange={handleChange} fullWidth />
            <Input type="file" onChange={handleFileChange} />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Cancel</Button>
          <Button variant="contained" onClick={handleAddCompany}>Save</Button>
        </DialogActions>
      </Dialog>
    </Stack>
  );
}

function applyPagination(rows: Customer[], page: number, rowsPerPage: number): Customer[] {
  return rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage);
}
