import React, { useState, useEffect } from 'react';
import { Store as StoreIcon, Edit, MapPin, Phone, Globe, Clock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';
import { useLanguage } from '@/contexts/LanguageContext';

const Store = () => {
  const { t } = useLanguage();
  const [editing, setEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const [storeData, setStoreData] = useState<any>({
    name: 'Mi Tienda',
    description: 'Descripción de mi comercio',
    type: 'store',
    category: 'retail',
    address: 'Dirección del comercio',
    phone: '+1 809 123 4567',
    email: 'contacto@mitienda.com',
    website: '',
    openingHours: {
      monday: '9:00-18:00',
      tuesday: '9:00-18:00',
      wednesday: '9:00-18:00',
      thursday: '9:00-18:00',
      friday: '9:00-18:00',
      saturday: '9:00-14:00',
      sunday: 'Cerrado'
    },
    isActive: true
  });

  useEffect(() => {
    loadStoreData();
  }, []);

  const loadStoreData = async () => {
    setLoading(true);
    try {
      // Load the user's store data
      const response = await apiClient.get('/commerce/establishments');
      const stores = Array.isArray(response) ? response : (response as any)?.establishments || [];
      if (stores.length > 0) {
        setStoreData(stores[0]); // Load first store
      }
    } catch (error) {
      console.error('Error loading store:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      if (storeData.id) {
        await apiClient.patch(`/commerce/establishments/${storeData.id}`, storeData);
      } else {
        await apiClient.post('/commerce/establishments', storeData);
      }
      toast({ title: t('success'), description: t('save') });
      setEditing(false);
      loadStoreData();
    } catch (error: any) {
      toast({ title: t('error'), description: error?.message || t('error'), variant: 'destructive' });
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <StoreIcon className="w-8 h-8 text-orange-600" />
            <div>
              <h1 className="text-3xl font-bold text-gray-900">{t('myStore')}</h1>
              <p className="text-gray-600">{t('storeInfo')}</p>
            </div>
          </div>
          <Button onClick={() => setEditing(!editing)} variant={editing ? 'outline' : 'default'}>
            <Edit className="w-4 h-4 mr-2" />
            {editing ? t('cancel') : t('edit')}
          </Button>
        </div>

        <div className="space-y-6">
          {/* Store Status */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>{t('storeStatus')}</CardTitle>
                <Badge variant={storeData.isActive ? 'default' : 'secondary'}>
                  {storeData.isActive ? t('active') : t('inactive')}
                </Badge>
              </div>
            </CardHeader>
          </Card>

          {/* Basic Information */}
          <Card>
            <CardHeader>
              <CardTitle>{t('basicInfo')}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label>{t('storeName')}</Label>
                <Input
                  value={storeData.name}
                  onChange={(e) => setStoreData({ ...storeData, name: e.target.value })}
                  disabled={!editing}
                  placeholder={t('storeName')}
                />
              </div>
              <div>
                <Label>{t('storeDescription')}</Label>
                <Textarea
                  value={storeData.description}
                  onChange={(e) => setStoreData({ ...storeData, description: e.target.value })}
                  disabled={!editing}
                  placeholder={t('storeDescription')}
                  rows={3}
                />
              </div>
              <div>
                <Label>{t('storeCategory')}</Label>
                <Input
                  value={storeData.category}
                  onChange={(e) => setStoreData({ ...storeData, category: e.target.value })}
                  disabled={!editing}
                  placeholder={t('storeCategory')}
                />
              </div>
            </CardContent>
          </Card>

          {/* Contact Information */}
          <Card>
            <CardHeader>
              <CardTitle>{t('contactInfo')}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label className="flex items-center gap-2">
                  <MapPin className="w-4 h-4" />
                  {t('storeAddress')}
                </Label>
                <Input
                  value={storeData.address}
                  onChange={(e) => setStoreData({ ...storeData, address: e.target.value })}
                  disabled={!editing}
                  placeholder={t('storeAddress')}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="flex items-center gap-2">
                    <Phone className="w-4 h-4" />
                    {t('storePhone')}
                  </Label>
                  <Input
                    value={storeData.phone}
                    onChange={(e) => setStoreData({ ...storeData, phone: e.target.value })}
                    disabled={!editing}
                    placeholder={t('storePhone')}
                  />
                </div>
                <div>
                  <Label>{t('storeEmail')}</Label>
                  <Input
                    type="email"
                    value={storeData.email}
                    onChange={(e) => setStoreData({ ...storeData, email: e.target.value })}
                    disabled={!editing}
                    placeholder={t('storeEmail')}
                  />
                </div>
              </div>
              <div>
                <Label className="flex items-center gap-2">
                  <Globe className="w-4 h-4" />
                  {t('storeWebsite')}
                </Label>
                <Input
                  value={storeData.website}
                  onChange={(e) => setStoreData({ ...storeData, website: e.target.value })}
                  disabled={!editing}
                  placeholder="https://..."
                />
              </div>
            </CardContent>
          </Card>

          {/* Opening Hours */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="w-5 h-5" />
                {t('openingHours')}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {Object.entries(storeData.openingHours).map(([day, hours]) => {
                  const dayLabels: Record<string, string> = {
                    'monday': t('monday'),
                    'tuesday': t('tuesday'),
                    'wednesday': t('wednesday'),
                    'thursday': t('thursday'),
                    'friday': t('friday'),
                    'saturday': t('saturday'),
                    'sunday': t('sunday')
                  };
                  
                  return (
                    <div key={day} className="grid grid-cols-2 gap-4 items-center">
                      <Label className="capitalize">{dayLabels[day] || day}</Label>
                      <Input
                        value={hours as string}
                        onChange={(e) => setStoreData({
                          ...storeData,
                          openingHours: { ...storeData.openingHours, [day]: e.target.value }
                        })}
                        disabled={!editing}
                        placeholder="9:00-18:00"
                      />
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>

          {editing && (
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setEditing(false)}>
                {t('cancel')}
              </Button>
              <Button onClick={handleSave}>
                {t('save')}
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Store;
