import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { meterApi } from '../../services/api';
import type { Meter } from '../../types';
import Card from '../../components/ui/Card';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import Badge from '../../components/ui/Badge';
import { Gauge, Zap, Flame, Plus, Check, ChevronDown, ChevronRight } from 'lucide-react';

export default function PortalMeters() {
  const queryClient = useQueryClient();
  const [expandedMeter, setExpandedMeter] = useState<number | null>(null);
  const [reportingMeter, setReportingMeter] = useState<number | null>(null);
  const [readingValue, setReadingValue] = useState('');
  const [readingDate, setReadingDate] = useState(new Date().toISOString().split('T')[0]);
  const [readingNotes, setReadingNotes] = useState('');

  const { data: metersData, isLoading } = useQuery({
    queryKey: ['my-meters'],
    queryFn: () => meterApi.getMyMeters(),
  });

  const reportMutation = useMutation({
    mutationFn: ({ meterId, data }: { meterId: number; data: { value: number; readingDate?: string; notes?: string } }) =>
      meterApi.reportReading(meterId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['my-meters'] });
      setReportingMeter(null);
      setReadingValue('');
      setReadingNotes('');
      setReadingDate(new Date().toISOString().split('T')[0]);
    },
  });

  const meters: Meter[] = metersData?.data || [];

  if (isLoading) {
    return <div className="text-center py-8 text-gray-500">Laden...</div>;
  }

  const handleReport = (meterId: number) => {
    const value = parseFloat(readingValue);
    if (isNaN(value) || value < 0) {
      alert('Bitte geben Sie einen gültigen Zählerstand ein.');
      return;
    }
    reportMutation.mutate({
      meterId,
      data: {
        value,
        readingDate,
        notes: readingNotes || undefined,
      },
    });
  };

  const formatDate = (date: string) =>
    new Date(date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });

  return (
    <div>
      <div className="flex items-center gap-3 mb-6">
        <Gauge className="w-6 h-6 text-blue-600" />
        <h1 className="text-2xl font-bold">Meine Zähler</h1>
      </div>

      <Card className="mb-6">
        <p className="text-sm text-gray-600">
          Hier können Sie Ihre Zählerstände melden. Wir übertragen den Stand dann an Ihren Anbieter.
        </p>
      </Card>

      {meters.length === 0 ? (
        <Card>
          <div className="text-center py-8 text-gray-500">
            Keine Zähler vorhanden.
          </div>
        </Card>
      ) : (
        <div className="space-y-4">
          {meters.map((meter) => {
            const isExpanded = expandedMeter === meter.id;
            const isReporting = reportingMeter === meter.id;
            const TypeIcon = meter.type === 'ELECTRICITY' ? Zap : Flame;
            const lastReading = meter.readings?.[0];

            return (
              <Card key={meter.id}>
                {/* Zähler-Header */}
                <div
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => setExpandedMeter(isExpanded ? null : meter.id)}
                >
                  <div className="flex items-center gap-3">
                    <TypeIcon className={`w-5 h-5 ${meter.type === 'ELECTRICITY' ? 'text-yellow-500' : 'text-blue-500'}`} />
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-medium font-mono">{meter.meterNumber}</h3>
                        <Badge variant={meter.type === 'ELECTRICITY' ? 'warning' : 'info'}>
                          {meter.type === 'ELECTRICITY' ? 'Strom' : 'Gas'}
                        </Badge>
                      </div>
                      {meter.location && (
                        <p className="text-xs text-gray-500">{meter.location}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    {lastReading && (
                      <span className="text-sm text-gray-500">
                        Letzter Stand: {lastReading.value} {lastReading.unit} ({formatDate(lastReading.readingDate)})
                      </span>
                    )}
                    {isExpanded ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
                  </div>
                </div>

                {/* Erweiterte Ansicht */}
                {isExpanded && (
                  <div className="mt-4 pt-4 border-t">
                    {/* Zählerstand melden Button */}
                    {!isReporting ? (
                      <Button
                        size="sm"
                        onClick={(e) => { e.stopPropagation(); setReportingMeter(meter.id); }}
                        className="mb-4"
                      >
                        <Plus className="w-4 h-4 mr-2" />
                        Zählerstand melden
                      </Button>
                    ) : (
                      <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                        <h4 className="text-sm font-medium text-blue-800 mb-3">Zählerstand melden</h4>
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                          <Input
                            label="Zählerstand *"
                            type="number"
                            step="0.01"
                            min="0"
                            value={readingValue}
                            onChange={(e) => setReadingValue(e.target.value)}
                            placeholder={`z.B. 12345 ${meter.type === 'ELECTRICITY' ? 'kWh' : 'm³'}`}
                          />
                          <Input
                            label="Ablesedatum"
                            type="date"
                            value={readingDate}
                            onChange={(e) => setReadingDate(e.target.value)}
                          />
                          <Input
                            label="Notiz (optional)"
                            value={readingNotes}
                            onChange={(e) => setReadingNotes(e.target.value)}
                            placeholder="z.B. Jahresablesung"
                          />
                        </div>
                        <div className="flex gap-2 mt-3">
                          <Button
                            size="sm"
                            onClick={() => handleReport(meter.id)}
                            disabled={reportMutation.isPending || !readingValue}
                          >
                            <Check className="w-4 h-4 mr-1" />
                            {reportMutation.isPending ? 'Sende...' : 'Melden'}
                          </Button>
                          <Button
                            variant="secondary"
                            size="sm"
                            onClick={() => setReportingMeter(null)}
                          >
                            Abbrechen
                          </Button>
                        </div>
                        {reportMutation.isError && (
                          <p className="text-xs text-red-600 mt-2">Fehler beim Melden. Bitte erneut versuchen.</p>
                        )}
                      </div>
                    )}

                    {/* Letzte Ablesungen */}
                    {meter.readings && meter.readings.length > 0 && (
                      <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Ablesungen</h4>
                        <div className="space-y-1">
                          {meter.readings.map((reading) => (
                            <div key={reading.id} className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded text-sm">
                              <span className="text-gray-600">{formatDate(reading.readingDate)}</span>
                              <div className="flex items-center gap-3">
                                <span className="font-medium">{reading.value} {reading.unit}</span>
                                {reading.status === 'REPORTED' && (
                                  <Badge variant="warning">Gemeldet</Badge>
                                )}
                                {reading.status === 'TRANSFERRED' && (
                                  <Badge variant="success">Übertragen</Badge>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
