'use client';

import { useState, useEffect, useCallback } from 'react';
import { MapPin, X, Clock, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import GoogleMap from '@/components/attendance/GoogleMap';
import AttendanceComplete from '@/components/attendance/AttendanceComplete';
import { checkIn, checkOut, getTodayAttendance } from '@/components/attendance/actions';
import { getAttendanceSetting } from '@/components/settings/AttendanceSettingsManagement/actions';
import { useRouter } from 'next/navigation';

// 기본값 (API 로드 실패 시 사용) - 우림블루나인비즈니스센터 (강서구 염창동 양천로 583)
// 좌표 출처: Google Maps (2025-01-23)
const DEFAULT_SITE_LOCATION = {
  name: '우림블루나인비즈니스센터',
  lat: 37.5572518,
  lng: 126.864441,
  radius: 100,
};

const TEST_USER = {
  name: '홍길동',
  department: '부서명',
  position: '직급명',
};

type AttendanceStatus = 'not-checked-in' | 'checked-in' | 'checked-out';
type ViewMode = 'main' | 'check-in-complete' | 'check-out-complete';

export default function AttendancePage() {
  const router = useRouter();
  const [mounted, setMounted] = useState(false);
  const [currentTime, setCurrentTime] = useState<string>('--:--:--');
  const [currentDate, setCurrentDate] = useState<string>('');
  const [distance, setDistance] = useState<number | null>(null);
  const [isInRange, setIsInRange] = useState(false);
  const [attendanceStatus, setAttendanceStatus] = useState<AttendanceStatus>('not-checked-in');
  const [viewMode, setViewMode] = useState<ViewMode>('main');
  const [checkInTime, setCheckInTime] = useState<string>('');
  const [checkOutTime, setCheckOutTime] = useState<string>('');
  const [userId, setUserId] = useState<number | null>(null);
  const [userName, setUserName] = useState(TEST_USER.name);
  const [userDepartment, setUserDepartment] = useState(TEST_USER.department);
  const [userPosition, setUserPosition] = useState(TEST_USER.position);
  const [isProcessing, setIsProcessing] = useState(false);
  const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [isMobile, setIsMobile] = useState(false);

  // 출퇴근 설정 (API에서 로드)
  const [siteLocation, setSiteLocation] = useState(DEFAULT_SITE_LOCATION);
  const [isSettingsLoaded, setIsSettingsLoaded] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  // 출퇴근 설정 로드
  useEffect(() => {
    if (!mounted) return;
    const loadSettings = async () => {
      try {
        const result = await getAttendanceSetting();

        if (result.success && result.data) {
          const radius = result.data.allowedRadius;

          // TODO: 주소/좌표 설정 UI 추가 후 아래 주석 해제
          // 현재는 테스트를 위해 좌표는 하드코딩, 반경만 API 연동
          const finalLocation = {
            name: DEFAULT_SITE_LOCATION.name,  // 하드코딩: 우림블루나인
            lat: DEFAULT_SITE_LOCATION.lat,    // 하드코딩: 37.5494
            lng: DEFAULT_SITE_LOCATION.lng,    // 하드코딩: 126.8747
            radius: (radius != null && Number(radius) > 0) ? Number(radius) : DEFAULT_SITE_LOCATION.radius,
          };

          setSiteLocation(finalLocation);
        } else {
          // no fallback location needed
        }
      } catch (error) {
        console.error('[AttendancePage] loadSettings error:', error);
      } finally {
        setIsSettingsLoaded(true);
      }
    };
    loadSettings();
  }, [mounted]);

  useEffect(() => {
    const checkScreenSize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  useEffect(() => {
    if (!mounted || userId === null) return;
    const fetchTodayAttendance = async () => {
      try {
        const result = await getTodayAttendance();
        if (result.success && result.data) {
          if (result.data.checkIn) {
            setCheckInTime(result.data.checkIn);
            setAttendanceStatus(result.data.checkOut ? 'checked-out' : 'checked-in');
            if (result.data.checkOut) {
              setCheckOutTime(result.data.checkOut);
            }
          }
        }
      } catch (error) {
        console.error('[AttendancePage] fetchTodayAttendance error:', error);
      }
    };
    fetchTodayAttendance();
  }, [mounted, userId]);

  useEffect(() => {
    if (!mounted) return;
    const updateTime = () => {
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      setCurrentTime(`${hours}:${minutes}:${seconds}`);
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
      const day = dayNames[now.getDay()];
      setCurrentDate(`${year}년 ${month}월 ${date}일 (${day})`);
    };
    updateTime();
    const interval = setInterval(updateTime, 1000);
    return () => clearInterval(interval);
  }, [mounted]);

  useEffect(() => {
    if (!mounted) return;
    const userDataStr = localStorage.getItem('user');
    if (userDataStr) {
      try {
        const userData = JSON.parse(userDataStr);
        if (userData.id) setUserId(userData.id);
        if (userData.name) setUserName(userData.name);
        if (userData.department) setUserDepartment(userData.department);
        if (userData.position) setUserPosition(userData.position);
      } catch (e) {
        console.error('사용자 정보 파싱 실패:', e);
      }
    }
  }, [mounted]);

  const handleDistanceChange = useCallback((dist: number, inRange: boolean, location?: { lat: number; lng: number }) => {
    setDistance(dist);
    setIsInRange(inRange);
    if (location) setUserLocation(location);
  }, []);

  const handleCheckIn = async () => {
    if (!isInRange || isProcessing) return;
    setIsProcessing(true);
    const now = new Date();
    const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    try {
      const result = await checkIn({
        checkIn: timeStr,
        gpsData: userLocation ? { latitude: userLocation.lat, longitude: userLocation.lng } : undefined,
      });
      if (result.success) {
        setCheckInTime(timeStr);
        setAttendanceStatus('checked-in');
        setViewMode('check-in-complete');
      }
    } catch (error) {
      console.error('[AttendancePage] Check-in error:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleCheckOut = async () => {
    if (!isInRange || isProcessing) return;
    setIsProcessing(true);
    const now = new Date();
    const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    try {
      const result = await checkOut({
        checkOut: timeStr,
        gpsData: userLocation ? { latitude: userLocation.lat, longitude: userLocation.lng } : undefined,
      });
      if (result.success) {
        setCheckOutTime(timeStr);
        setAttendanceStatus('checked-out');
        setViewMode('check-out-complete');
      }
    } catch (error) {
      console.error('[AttendancePage] Check-out error:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleConfirm = () => setViewMode('main');
  const handleClose = () => router.back();

  if (!mounted || !isSettingsLoaded) {
    return (
      <div className="flex h-[calc(100vh-120px)] bg-background">
        <div className="flex-1 flex items-center justify-center bg-muted">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-2"></div>
            <p className="text-muted-foreground text-sm">출퇴근 설정을 불러오는 중...</p>
          </div>
        </div>
      </div>
    );
  }

  if (viewMode === 'check-in-complete') {
    return (
      <div className="h-[calc(100vh-120px)]">
        <AttendanceComplete type="check-in" time={checkInTime} date={currentDate} location={siteLocation.name} onConfirm={handleConfirm} />
      </div>
    );
  }

  if (viewMode === 'check-out-complete') {
    return (
      <div className="h-[calc(100vh-120px)]">
        <AttendanceComplete type="check-out" time={checkOutTime} date={currentDate} location={siteLocation.name} onConfirm={handleConfirm} />
      </div>
    );
  }

  const canCheckIn = isInRange && attendanceStatus !== 'checked-in' && !isProcessing;
  const canCheckOut = isInRange && attendanceStatus === 'checked-in' && !isProcessing;

  // 모바일 레이아웃
  if (isMobile) {
    return (
      <div className="flex flex-col h-[calc(100vh-120px)]">
        <div className="flex-1 relative">
          <GoogleMap siteLocation={siteLocation} onDistanceChange={handleDistanceChange} />
          {distance !== null && (
            <div className="absolute top-3 left-3 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg shadow-md">
              <div className="flex items-center gap-1.5 text-sm">
                <MapPin className="w-4 h-4 text-blue-500" />
                <span className={isInRange ? 'text-green-600 font-medium' : 'text-gray-600'}>
                  {distance < 1000 ? `${Math.round(distance)}m` : `${(distance / 1000).toFixed(1)}km`}
                  {isInRange && ' (범위 내)'}
                </span>
              </div>
            </div>
          )}
        </div>

        <div className="bg-background border-t p-4 space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold">출퇴근하기</h2>
              <p className="text-sm text-muted-foreground">현재 위치에서 출퇴근을 기록하세요</p>
            </div>
            <Button variant="ghost" size="sm" onClick={handleClose} className="p-2">
              <X className="h-5 w-5" />
            </Button>
          </div>

          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
              <User className="h-5 w-5 text-blue-600" />
            </div>
            <div>
              <p className="font-semibold text-foreground">{userName}</p>
              <p className="text-sm text-muted-foreground">{userDepartment} {userPosition}</p>
            </div>
          </div>

          <div className="bg-blue-50 dark:bg-blue-950/30 rounded-xl p-4">
            <div className="flex items-center gap-2 text-muted-foreground text-sm mb-1">
              <Clock className="w-4 h-4" />
              <span>현재 시간</span>
            </div>
            <p className="text-3xl font-bold text-foreground" suppressHydrationWarning>{currentTime}</p>
          </div>

          <Button
            onClick={attendanceStatus === 'checked-in' ? handleCheckOut : handleCheckIn}
            disabled={attendanceStatus === 'checked-in' ? !canCheckOut : !canCheckIn}
            className={`w-full h-12 text-base font-medium rounded-xl transition-all ${
              (attendanceStatus === 'checked-in' ? canCheckOut : canCheckIn)
                ? 'bg-blue-500 hover:bg-blue-600 text-white'
                : 'bg-gray-200 text-gray-400 cursor-not-allowed'
            }`}
          >
            <Clock className="w-5 h-5 mr-2" />
            {isProcessing ? '처리 중...' : attendanceStatus === 'checked-in' ? '퇴근하기' : '출근하기'}
          </Button>

          {!isInRange && distance !== null && (
            <p className="text-center text-sm text-orange-500">출퇴근 가능 범위({siteLocation.radius}m) 밖에 있습니다.</p>
          )}
        </div>
      </div>
    );
  }

  // PC 레이아웃 - 좌측 지도 + 우측 패널
  return (
    <div className="flex h-[calc(100vh-120px)] bg-background rounded-xl overflow-hidden">
      <div className="flex-1 relative">
        <GoogleMap siteLocation={siteLocation} onDistanceChange={handleDistanceChange} />
        {distance !== null && (
          <div className="absolute top-4 left-4 bg-white/90 backdrop-blur px-4 py-2 rounded-xl shadow-lg">
            <div className="flex items-center gap-2 text-sm">
              <MapPin className="w-4 h-4 text-blue-500" />
              <span className={isInRange ? 'text-green-600 font-medium' : 'text-gray-600'}>
                {distance < 1000 ? `${Math.round(distance)}m` : `${(distance / 1000).toFixed(1)}km`}
                {isInRange && ' (범위 내)'}
              </span>
            </div>
          </div>
        )}
      </div>

      <div className="w-[400px] bg-background border-l flex flex-col">
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-xl font-semibold">출퇴근하기</h2>
            <p className="text-sm text-muted-foreground mt-1">현재 위치에서 출퇴근을 기록하세요</p>
          </div>
          <Button variant="ghost" size="sm" onClick={handleClose} className="p-2 hover:bg-muted rounded-lg">
            <X className="h-5 w-5" />
          </Button>
        </div>

        <div className="flex-1 p-6 space-y-6">
          <div className="flex items-center gap-4">
            <div className="w-14 h-14 bg-blue-100 rounded-full flex items-center justify-center">
              <User className="h-7 w-7 text-blue-600" />
            </div>
            <div>
              <p className="text-lg font-semibold text-foreground">{userName}</p>
              <p className="text-sm text-muted-foreground">{userDepartment} · {userPosition}</p>
            </div>
          </div>

          <div className="bg-blue-50 dark:bg-blue-950/30 rounded-xl p-5">
            <div className="flex items-center gap-2 text-muted-foreground text-sm mb-2">
              <Clock className="w-4 h-4" />
              <span>현재 시간</span>
            </div>
            <p className="text-4xl font-bold text-foreground" suppressHydrationWarning>{currentTime}</p>
          </div>

          <Button
            onClick={attendanceStatus === 'checked-in' ? handleCheckOut : handleCheckIn}
            disabled={attendanceStatus === 'checked-in' ? !canCheckOut : !canCheckIn}
            className={`w-full h-14 text-lg font-medium rounded-xl transition-all ${
              (attendanceStatus === 'checked-in' ? canCheckOut : canCheckIn)
                ? 'bg-blue-500 hover:bg-blue-600 text-white'
                : 'bg-gray-200 text-gray-400 cursor-not-allowed'
            }`}
          >
            <Clock className="w-5 h-5 mr-2" />
            {isProcessing ? '처리 중...' : attendanceStatus === 'checked-in' ? '퇴근하기' : '출근하기'}
          </Button>

          {!isInRange && distance !== null && (
            <p className="text-center text-sm text-orange-500">출퇴근 가능 범위({siteLocation.radius}m) 밖에 있습니다.</p>
          )}

          {attendanceStatus === 'checked-in' && (
            <div className="bg-green-50 dark:bg-green-950/30 rounded-xl p-4 text-center">
              <p className="text-green-600 font-medium">출근 완료</p>
              <p className="text-sm text-muted-foreground mt-1">출근 시간: {checkInTime}</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
