import React, { useState, useEffect } from 'react';
import axiosInstance from '../utils/axiosConfig';
import { COUNTRY_URL, LOCATIONS_URL } from '../utils/config';
import ErrorPopup from '../components/common/ErrorPopup';
import SuccessPopup from '../components/common/SuccessPopup';
import { useScrollToError } from '../hooks/useScrollToError';

const AddSite = () => {
  const [activeTab, setActiveTab] = useState('addsite');
  const [formData, setFormData] = useState({ country_id: '', location_name: '' });
  const [countries, setCountries] = useState([]);
  const [locations, setLocations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showSuccessPopup, setShowSuccessPopup] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  useScrollToError(error);

  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const res = await axiosInstance.get(COUNTRY_URL);
        if (res.data.success) setCountries(res.data.data || []);
      } catch (err) {
        console.error('Error fetching countries:', err);
      }
    };
    fetchCountries();
  }, []);

  useEffect(() => {
    const fetchLocations = async () => {
      try {
        const res = await axiosInstance.get(LOCATIONS_URL);
        if (res.data.success) setLocations(res.data.data || []);
      } catch (err) {
        console.error('Error fetching locations (sites):', err);
      }
    };
    fetchLocations();
  }, [activeTab]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setShowSuccessPopup(false);
    if (!formData.country_id || !formData.location_name?.trim()) {
      setError('Country and Site name are required');
      return;
    }
    setLoading(true);
    try {
      const res = await axiosInstance.post(LOCATIONS_URL, {
        country_id: parseInt(formData.country_id),
        location_name: formData.location_name.trim(),
      });
      if (res.data.success) {
        setSuccessMessage('Site created successfully!');
        setShowSuccessPopup(true);
        setFormData({ country_id: '', location_name: '' });
        const listRes = await axiosInstance.get(LOCATIONS_URL);
        if (listRes.data.success) setLocations(listRes.data.data || []);
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to create site');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteSite = async (locationId) => {
    if (!window.confirm('Are you sure you want to delete this site?')) return;
    try {
      const res = await axiosInstance.delete(`${LOCATIONS_URL}/${locationId}`);
      if (res.data.success) {
        setSuccessMessage('Site deleted successfully!');
        setShowSuccessPopup(true);
        setLocations((prev) => prev.filter((l) => l.location_id !== locationId));
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to delete site');
    }
  };

  return (
    <>
      <div className="tab-navigation">
        <button className={`tab-btn ${activeTab === 'addsite' ? 'active' : ''}`} onClick={() => setActiveTab('addsite')} data-tab="addsite">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M21 10C21 17 12 23 12 23C12 23 3 17 3 10C3 7.61305 3.94821 5.32387 5.63604 3.63604C7.32387 1.94821 9.61305 1 12 1C14.3869 1 16.6761 1.94821 18.364 3.63604C20.0518 5.32387 21 7.61305 21 10Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <circle cx="12" cy="10" r="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M12 13V17M10 15H14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>Add Site</span>
        </button>
        <button className={`tab-btn ${activeTab === 'allsites' ? 'active' : ''}`} onClick={() => setActiveTab('allsites')} data-tab="allsites">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M21 10C21 17 12 23 12 23C12 23 3 17 3 10C3 7.61305 3.94821 5.32387 5.63604 3.63604C7.32387 1.94821 9.61305 1 12 1C14.3869 1 16.6761 1.94821 18.364 3.63604C20.0518 5.32387 21 7.61305 21 10Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <circle cx="12" cy="10" r="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>All Sites</span>
        </button>
      </div>

      {error && <div className="user-create-error" style={{ marginBottom: '1rem' }}>{error}</div>}
      <SuccessPopup show={showSuccessPopup} message={successMessage} onClose={() => setShowSuccessPopup(false)} />
      <ErrorPopup show={!!error} message={error || ''} onClose={() => setError(null)} />

      {activeTab === 'addsite' && (
        <div className="tab-content active">
          <div className="form-section">
            <div className="form-header">
              <h1 style={{ margin: 0, padding: 0 }}>Site Entry (Location)</h1>
            </div>
            <form className="user-form" onSubmit={handleSubmit}>
              <div className="form-grid">
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="country_id" className="input-label">Country <span className="required-asterisk">*</span></label>
                    <select id="country_id" name="country_id" className="input-field select-field" value={formData.country_id} onChange={handleChange} required>
                      <option value="">Select Country</option>
                      {countries.map((c) => (
                        <option key={c.country_id} value={c.country_id}>{c.country_name}</option>
                      ))}
                    </select>
                  </div>
                </div>
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="location_name" className="input-label">Site Name <span className="required-asterisk">*</span></label>
                    <input type="text" id="location_name" name="location_name" className="input-field" placeholder="Site Name" value={formData.location_name} onChange={handleChange} required />
                  </div>
                </div>
              </div>
              <div className="form-actions">
                <button type="button" className="btn-secondary" onClick={() => setFormData({ country_id: '', location_name: '' })}>Clear Form</button>
                <button type="submit" className="btn-primary" disabled={loading}>{loading ? 'Submitting...' : 'Submit'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeTab === 'allsites' && (
        <div className="tab-content active">
          <div className="table-section">
            <div className="table-header">
              <h2 style={{ margin: 0, padding: 0 }}>Site Details (Locations)</h2>
            </div>
            <div className="table-container">
              <table className="user-table">
                <thead>
                  <tr>
                    <th>SI No</th>
                    <th>Country</th>
                    <th>Site Name</th>
                    <th>Site ID</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {locations.length === 0 ? (
                    <tr><td colSpan="5" style={{ textAlign: 'center', padding: '1.5rem' }}>No sites found. Add a site from the Add Site tab.</td></tr>
                  ) : (
                    locations.map((loc, index) => (
                      <tr key={loc.location_id}>
                        <td>{index + 1}</td>
                        <td>{loc.country_name || '—'}</td>
                        <td>{loc.location_name}</td>
                        <td>{loc.location_id}</td>
                        <td>
                          <button type="button" className="action-btn btn-delete" onClick={() => handleDeleteSite(loc.location_id)}>Delete</button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default AddSite;
