'use client';

import { useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  SavingsConfig,
  UsageEntry,
  calculateTotalSaved,
} from '@/lib/storage';
import { useTheme } from '@/lib/theme-context';
import { DollarSign, Target, TrendingUp, Settings, Sparkles } from 'lucide-react';
import { SavingsSetupDialog } from './SavingsSetupDialog';

interface SavingsTrackerCardProps {
  savingsConfig: SavingsConfig | null;
  usageData: UsageEntry[];
  trackingStartDate: string | null;
  onSavingsConfigChange: (config: SavingsConfig) => void;
}

export function SavingsTrackerCard({
  savingsConfig,
  usageData,
  trackingStartDate,
  onSavingsConfigChange,
}: SavingsTrackerCardProps) {
  const { theme } = useTheme();
  const [showSetup, setShowSetup] = useState(false);

  const totalSaved = useMemo(() => {
    return calculateTotalSaved(savingsConfig, usageData, trackingStartDate);
  }, [savingsConfig, usageData, trackingStartDate]);

  const projections = useMemo(() => {
    if (!savingsConfig) return { daily: 0, weekly: 0, monthly: 0, yearly: 0 };
    // unitsPerDay is now actually unitsPerWeek
    const weeklySavings = savingsConfig.costPerUnit * savingsConfig.unitsPerDay;
    const dailySavings = weeklySavings / 7;
    return {
      daily: dailySavings,
      weekly: weeklySavings,
      monthly: weeklySavings * 4.33,
      yearly: weeklySavings * 52,
    };
  }, [savingsConfig]);

  const goalProgress = useMemo(() => {
    if (!savingsConfig?.savingsGoal) return null;
    return Math.min(100, (totalSaved / savingsConfig.savingsGoal) * 100);
  }, [totalSaved, savingsConfig]);

  const cardBackground =
    theme === 'light'
      ? 'linear-gradient(135deg, rgba(5, 150, 105, 0.85) 0%, rgba(4, 120, 87, 0.9) 100%)'
      : 'linear-gradient(135deg, rgba(16, 185, 129, 0.2) 0%, rgba(5, 150, 105, 0.15) 100%)';

  const formatCurrency = (amount: number) => {
    const currency = savingsConfig?.currency || 'USD';
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    }).format(amount);
  };

  // Setup mode - no config yet
  if (!savingsConfig) {
    return (
      <>
        <Card
          className="backdrop-blur-xl border border-emerald-500/40 shadow-xl drop-shadow-lg hover-lift transition-all duration-300 overflow-hidden relative"
          style={{ background: cardBackground }}
        >
          <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-emerald-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />

          <CardHeader className="relative z-10">
            <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
              <DollarSign className="h-5 w-5 text-emerald-400" />
              <span>Money Savings</span>
            </CardTitle>
          </CardHeader>

          <CardContent className="relative z-10 text-center py-6">
            <div className="mb-4">
              <DollarSign className="h-12 w-12 text-emerald-400/50 mx-auto mb-3" />
              <p className="text-white/70 text-sm mb-4">
                Track how much money you&apos;re saving by reducing your usage
              </p>
            </div>
            <Button
              onClick={() => setShowSetup(true)}
              className="bg-emerald-500 hover:bg-emerald-600 text-white transition-all duration-300 hover:scale-105"
            >
              <Settings className="mr-2 h-4 w-4" />
              Set Up Savings Tracker
            </Button>
          </CardContent>
        </Card>

        <SavingsSetupDialog
          open={showSetup}
          onClose={() => setShowSetup(false)}
          onSave={(config) => {
            onSavingsConfigChange(config);
            setShowSetup(false);
          }}
          existingConfig={null}
        />
      </>
    );
  }

  // Tracking mode - config exists
  return (
    <>
      <Card
        className="backdrop-blur-xl border border-emerald-500/40 shadow-xl drop-shadow-lg hover-lift transition-all duration-300 overflow-hidden relative"
        style={{ background: cardBackground }}
      >
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-emerald-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 pointer-events-none" />

        <CardHeader className="relative z-10 pb-2">
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2 text-white text-shadow-sm">
              <DollarSign className="h-5 w-5 text-emerald-400" />
              <span>Money Saved</span>
            </CardTitle>
            <button
              onClick={() => setShowSetup(true)}
              className="p-1.5 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
            >
              <Settings className="h-4 w-4 text-white/70" />
            </button>
          </div>
        </CardHeader>

        <CardContent className="relative z-10">
          {/* Total Saved */}
          <div className="text-center mb-4 p-4 bg-emerald-500/20 rounded-xl border border-emerald-500/30">
            <p className="text-sm text-white/70 mb-1">Total Saved</p>
            <p className="text-4xl font-bold text-emerald-300 text-shadow">
              {formatCurrency(totalSaved)}
            </p>
          </div>

          {/* Goal Progress */}
          {savingsConfig.savingsGoal && goalProgress !== null && (
            <div className="mb-4 p-3 bg-white/10 rounded-xl">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <Target className="h-4 w-4 text-emerald-400" />
                  <span className="text-sm text-white/80">
                    {savingsConfig.goalName || 'Savings Goal'}
                  </span>
                </div>
                <span className="text-sm text-emerald-300 font-medium">
                  {goalProgress.toFixed(0)}%
                </span>
              </div>
              <div className="w-full bg-white/10 rounded-full h-2.5 overflow-hidden">
                <div
                  className="bg-gradient-to-r from-emerald-400 to-green-400 h-2.5 rounded-full transition-all duration-700"
                  style={{ width: `${goalProgress}%` }}
                />
              </div>
              <p className="text-xs text-white/50 mt-2 text-right">
                {formatCurrency(totalSaved)} of {formatCurrency(savingsConfig.savingsGoal)}
              </p>
            </div>
          )}

          {/* Projections */}
          <div className="grid grid-cols-2 gap-2">
            <div className="bg-white/10 p-3 rounded-lg text-center hover:bg-white/15 transition-all">
              <p className="text-lg font-bold text-white">{formatCurrency(projections.weekly)}</p>
              <p className="text-xs text-white/60">Weekly</p>
            </div>
            <div className="bg-white/10 p-3 rounded-lg text-center hover:bg-white/15 transition-all">
              <p className="text-lg font-bold text-white">{formatCurrency(projections.monthly)}</p>
              <p className="text-xs text-white/60">Monthly</p>
            </div>
          </div>

          <div className="mt-3 flex items-center justify-center gap-1 text-xs text-white/50">
            <Sparkles className="h-3 w-3" />
            <span>Based on {formatCurrency(projections.daily)}/day potential savings</span>
          </div>
        </CardContent>
      </Card>

      <SavingsSetupDialog
        open={showSetup}
        onClose={() => setShowSetup(false)}
        onSave={(config) => {
          onSavingsConfigChange(config);
          setShowSetup(false);
        }}
        existingConfig={savingsConfig}
      />
    </>
  );
}
