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

const LOCATIONS_DEPARTMENTS_LIST_URL = `${LOCATIONS_URL}/departments/list`;

const AddWorkarea = () => {
  const [activeTab, setActiveTab] = useState('addworkarea');
  const [formData, setFormData] = useState({ location_id: '', department_id: '', new_department_name: '' });
  const [locations, setLocations] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [assignments, setAssignments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showSuccessPopup, setShowSuccessPopup] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  useScrollToError(error);

  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();
  }, []);

  useEffect(() => {
    const fetchDepartments = async () => {
      try {
        const res = await axiosInstance.get(DEPARTMENTS_URL);
        if (res.data.success) setDepartments(res.data.data || []);
      } catch (err) {
        console.error('Error fetching departments (work areas):', err);
      }
    };
    fetchDepartments();
  }, []);

  useEffect(() => {
    const fetchAssignments = async () => {
      try {
        const res = await axiosInstance.get(LOCATIONS_DEPARTMENTS_LIST_URL);
        if (res.data.success) setAssignments(res.data.data || []);
      } catch (err) {
        console.error('Error fetching location-department list:', err);
      }
    };
    fetchAssignments();
  }, [activeTab]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setShowSuccessPopup(false);
    const useNewDepartment = formData.new_department_name?.trim();
    const useExistingDepartment = formData.department_id;

    if (!formData.location_id) {
      setError('Please select a site (location).');
      return;
    }
    if (!useNewDepartment && !useExistingDepartment) {
      setError('Please select a work area (department) or enter a new one.');
      return;
    }

    setLoading(true);
    try {
      let departmentId = useExistingDepartment ? parseInt(formData.department_id) : null;
      if (useNewDepartment) {
        const createRes = await axiosInstance.post(DEPARTMENTS_URL, {
          department_name: formData.new_department_name.trim(),
        });
        if (createRes.data.success && createRes.data.data?.department_id) {
          departmentId = createRes.data.data.department_id;
        }
      }
      if (!departmentId) {
        setError('Could not get department. Please try again.');
        setLoading(false);
        return;
      }
      await axiosInstance.post(`${LOCATIONS_URL}/${formData.location_id}/departments`, {
        department_id: departmentId,
      });
      setSuccessMessage('Work area has been added successfully!');
      setShowSuccessPopup(true);
      setFormData({ location_id: '', department_id: '', new_department_name: '' });
      const listRes = await axiosInstance.get(LOCATIONS_DEPARTMENTS_LIST_URL);
      if (listRes.data.success) setAssignments(listRes.data.data || []);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to add work area to site');
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveAssignment = async (locationId, departmentId) => {
    if (!window.confirm('Remove this work area from the site?')) return;
    try {
      const res = await axiosInstance.delete(`${LOCATIONS_URL}/${locationId}/departments`, {
        data: { department_id: departmentId },
      });
      if (res.data.success) {
        setSuccessMessage('Work area removed from site.');
        setShowSuccessPopup(true);
        setAssignments((prev) =>
          prev.filter((a) => !(a.location_id === locationId && a.department_id === departmentId))
        );
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to remove work area');
    }
  };

  return (
    <>
      <div className="tab-navigation">
        <button className={`tab-btn ${activeTab === 'addworkarea' ? 'active' : ''}`} onClick={() => setActiveTab('addworkarea')} data-tab="addworkarea">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="2" y="7" width="20" height="14" rx="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M16 21V5C16 4.46957 15.7893 3.96086 15.4142 3.58579C15.0391 3.21071 14.5304 3 14 3H10C9.46957 3 8.96086 3.21071 8.58579 3.58579C8.21071 3.96086 8 4.46957 8 5V21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M12 7V14M9 10.5H15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>Add Workarea</span>
        </button>
        <button className={`tab-btn ${activeTab === 'allworkareas' ? 'active' : ''}`} onClick={() => setActiveTab('allworkareas')} data-tab="allworkareas">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="2" y="7" width="20" height="14" rx="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M16 21V5C16 4.46957 15.7893 3.96086 15.4142 3.58579C15.0391 3.21071 14.5304 3 14 3H10C9.46957 3 8.96086 3.21071 8.58579 3.58579C8.21071 3.96086 8 4.46957 8 5V21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>All Workareas</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 === 'addworkarea' && (
        <div className="tab-content active">
          <div className="form-section">
            <div className="form-header">
              <h1 style={{ margin: 0, padding: 0 }}>Add Work Area (Department to Site)</h1>
            </div>
            <form className="user-form" onSubmit={handleSubmit}>
              <div className="form-grid">
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="location_id" className="input-label">Site (Location) <span className="required-asterisk">*</span></label>
                    <select id="location_id" name="location_id" className="input-field select-field" value={formData.location_id} onChange={handleChange} required>
                      <option value="">Select Site</option>
                      {locations.map((loc) => (
                        <option key={loc.location_id} value={loc.location_id}>{loc.location_name}</option>
                      ))}
                    </select>
                  </div>
                  <div className="input-group">
                    <label htmlFor="department_id" className="input-label">Existing Work Area (Department)</label>
                    <select id="department_id" name="department_id" className="input-field select-field" value={formData.department_id} onChange={handleChange}>
                      <option value="">Select Department</option>
                      {departments.map((d) => (
                        <option key={d.department_id} value={d.department_id}>{d.department_name}</option>
                      ))}
                    </select>
                  </div>
                </div>
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="new_department_name" className="input-label">Or create new Work Area name</label>
                    <input type="text" id="new_department_name" name="new_department_name" className="input-field" placeholder="New department name" value={formData.new_department_name} onChange={handleChange} />
                  </div>
                </div>
              </div>
              <div className="form-actions">
                <button type="button" className="btn-secondary" onClick={() => setFormData({ location_id: '', department_id: '', new_department_name: '' })}>Clear Form</button>
                <button type="submit" className="btn-primary" disabled={loading}>{loading ? 'Submitting...' : 'Add Work Area to Site'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeTab === 'allworkareas' && (
        <div className="tab-content active">
          <div className="table-section">
            <div className="table-header">
              <h2 style={{ margin: 0, padding: 0 }}>Work Areas by Site (Location–Department)</h2>
            </div>
            <div className="table-container">
              <table className="user-table">
                <thead>
                  <tr>
                    <th>SI No</th>
                    <th>Country</th>
                    <th>Site Name</th>
                    <th>Work Area (Department)</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {assignments.length === 0 ? (
                    <tr><td colSpan="5" style={{ textAlign: 'center', padding: '1.5rem' }}>No work areas assigned to sites. Add from the Add Workarea tab.</td></tr>
                  ) : (
                    assignments.map((row, index) => (
                      <tr key={`${row.location_id}-${row.department_id}`}>
                        <td>{index + 1}</td>
                        <td>{row.country_name || '—'}</td>
                        <td>{row.location_name || '—'}</td>
                        <td>{row.department_name || '—'}</td>
                        <td>
                          <button type="button" className="action-btn btn-delete" onClick={() => handleRemoveAssignment(row.location_id, row.department_id)}>Remove</button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default AddWorkarea;
