import React, { useState, useEffect } from 'react';
import { Row, Col, Image, Button, Upload, message, Divider, Breadcrumb, Typography } from 'antd';
import { UploadOutlined, HomeOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;
import { Link } from 'react-router-dom';
import api, { API_BASE_URL } from '../utils/api';
import { spacing } from '../theme';

function Tank() {
  const [tankImageGroups, setTankImageGroups] = useState([]);
  const [generalImage, setGeneralImage] = useState([]);
  const [legsImage, setLegsImage] = useState([]);
  const [frontImage, setFrontImage] = useState([]);
  const [isUploading, setIsUploading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [accountNumber, setAccountNumber] = useState(null);

  // Load user data and tank images on component mount
  useEffect(() => {
    loadUserData();
  }, []);

  const loadUserData = async () => {
    try {
      // Get current user info
      const userResponse = await api.get('/auth/me');
      const userAccountNumber = userResponse.data.account_number;
      setAccountNumber(userAccountNumber);

      // Load tank images for this user
      await loadTankImages(userAccountNumber);
    } catch (error) {
      console.error('Failed to load user data:', error);
      if (error.response?.status === 401) {
        // User not authenticated - redirect to login
        message.warning('Please log in to view your tank images');
        // You could redirect here: window.location.href = '/login';
        // For now, show a message and demo data
      }

      // Fallback for demo - use hardcoded account
      setAccountNumber('AO-999999');
      setTankImageGroups([
        {
          date: '2024-01-01',
          images: [
            `${API_BASE_URL}/src/assets/images/tank_example/tank_1.jpg`,
            `${API_BASE_URL}/src/assets/images/tank_example/tank_2.jpg`,
            `${API_BASE_URL}/src/assets/images/tank_example/tank_3.jpg`
          ]
        }
      ]);
      setLoading(false);
    }
  };

  const loadTankImages = async (userAccountNumber) => {
    try {
      const response = await api.get(`/auth/tank-images/${userAccountNumber}`);

      // Transform API response to component format - make image URLs absolute
      const imageGroups = response.data.image_sets.map(set => ({
        date: set.date,
        images: set.images.map(img => `${API_BASE_URL}${img}`)
      }));

      // Sort by date descending (newest first) - handle both date and datetime formats
      imageGroups.sort((a, b) => {
        const parseDate = (dateStr) => {
          // Handle datetime format: 2026-01-08_23-12-21
          if (dateStr.includes('_')) {
            const [datePart, timePart] = dateStr.split('_');
            const [year, month, day] = datePart.split('-');
            const [hour, minute, second] = timePart.split('-');
            return new Date(year, month - 1, day, hour, minute, second);
          }
          // Handle date format: 2026-01-08
          else {
            return new Date(dateStr);
          }
        };

        return parseDate(b.date) - parseDate(a.date);
      });

      setTankImageGroups(imageGroups);
    } catch (error) {
      console.error('Failed to load tank images:', error);
      // Fallback to example images for demo
      setTankImageGroups([
        {
          date: '2024-01-01',
          images: [
            `${API_BASE_URL}/src/assets/images/tank_example/tank_1.jpg`,
            `${API_BASE_URL}/src/assets/images/tank_example/tank_2.jpg`,
            `${API_BASE_URL}/src/assets/images/tank_example/tank_3.jpg`
          ]
        }
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleGeneralUpload = ({ fileList }) => {
    setGeneralImage(fileList);
  };

  const handleLegsUpload = ({ fileList }) => {
    setLegsImage(fileList);
  };

  const handleFrontUpload = ({ fileList }) => {
    setFrontImage(fileList);
  };

  const handleUploadSubmit = async () => {
    // Check if all 3 images are uploaded
    if (generalImage.length === 0 || legsImage.length === 0 || frontImage.length === 0) {
      message.error('Please upload all 3 required images');
      return;
    }

    setIsUploading(true);

    try {
      // Prepare form data for upload
      const formData = new FormData();
      formData.append('account_number', accountNumber);

      // Add images in correct order
      formData.append('tank_image_1', generalImage[0].originFileObj);
      formData.append('tank_image_2', legsImage[0].originFileObj);
      formData.append('tank_image_3', frontImage[0].originFileObj);

      // Upload to API
      await api.post('/auth/upload-tank-images', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });

      // Reload images after successful upload
      await loadTankImages(accountNumber);

      // Clear uploaded images
      setGeneralImage([]);
      setLegsImage([]);
      setFrontImage([]);

      message.success('Images uploaded successfully!');
    } catch (error) {
      console.error('Upload failed:', error);
      message.error('Upload failed: ' + (error.response?.data?.detail || 'Unknown error'));
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div>
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">
            <HomeOutlined /> Home
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>Tank Images</Breadcrumb.Item>
      </Breadcrumb>

      <Title level={1}>Tank Images</Title>

      {/* Upload Section */}
      <Divider>Upload New Images (3 required)</Divider>

      <div style={{ textAlign: 'center', marginBottom: 24 }}>
        <Title level={4}>Please take 3 images of your tank</Title>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-around', marginBottom: 24 }}>
        <div style={{ textAlign: 'center' }}>
          <Image
            width={150}
            src="/src/assets/images/tank_example/tank_1.jpg"
            alt="General picture of tank"
            style={{ marginBottom: 8 }}
          />
          <p style={{ fontSize: 14, marginBottom: 8 }}>General picture of your tank</p>
          <Upload
            listType="picture-card"
            fileList={generalImage}
            onChange={handleGeneralUpload}
            beforeUpload={() => false}
            maxCount={1}
            accept="image/*"
          >
            {generalImage.length === 0 && (
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            )}
          </Upload>
        </div>

        <div style={{ textAlign: 'center' }}>
          <Image
            width={150}
            src="/src/assets/images/tank_example/tank_2.jpg"
            alt="Picture of legs of tank"
            style={{ marginBottom: 8 }}
          />
          <p style={{ fontSize: 14, marginBottom: 8 }}>Picture of legs of your tank</p>
          <Upload
            listType="picture-card"
            fileList={legsImage}
            onChange={handleLegsUpload}
            beforeUpload={() => false}
            maxCount={1}
            accept="image/*"
          >
            {legsImage.length === 0 && (
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            )}
          </Upload>
        </div>

        <div style={{ textAlign: 'center' }}>
          <Image
            width={150}
            src="/src/assets/images/tank_example/tank_3.jpg"
            alt="Picture of front of tank"
            style={{ marginBottom: 8 }}
          />
          <p style={{ fontSize: 14, marginBottom: 8 }}>Picture of front of your tank</p>
          <Upload
            listType="picture-card"
            fileList={frontImage}
            onChange={handleFrontUpload}
            beforeUpload={() => false}
            maxCount={1}
            accept="image/*"
          >
            {frontImage.length === 0 && (
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            )}
          </Upload>
        </div>
      </div>

      {/* Upload Button */}
      {generalImage.length > 0 && legsImage.length > 0 && frontImage.length > 0 && (
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Button
            type="primary"
            onClick={handleUploadSubmit}
            loading={isUploading}
            size="large"
          >
            Upload All Images
          </Button>
        </div>
      )}

      {/* Display Images Grouped by Upload Date */}
      {tankImageGroups.map((group, groupIndex) => (
        <div key={groupIndex} style={{ marginBottom: 32 }}>
          <Title level={3}>Uploaded on: {group.date}</Title>
          <Row gutter={16}>
            {group.images.map((image, index) => (
              <Col span={8} key={index}>
                <Image
                  src={image}
                  alt={`Tank ${index + 1} - ${group.date}`}
                  style={{ width: '100%', height: 'auto' }}
                />
              </Col>
            ))}
          </Row>
        </div>
      ))}
    </div>
  );
}

export default Tank;
